#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// list.ts — List keys in the vault under a prefix
//
// Part of: .opencode/skills/templating-vault/scripts/
//
// Lists keys that have value files. Supports recursive and immediate-only modes.
//
// USAGE:
//   list.ts --prefix <prefix> [--recursive] [--config <path>] [--store-dir <path>]
//   list.ts [--recursive]  (list all keys)
//
// OUTPUT (stdout): JSON result with keys array
// =============================================================================
import { fileURLToPath } from 'node:url';
import {
  parseCommonFlags, getFlag, hasFlag, output,
  loadConfig, listAllKeys,
} from './api.ts';

async function main(): Promise<void> {
  const { config: cfgPath, storeDirs, rest } = parseCommonFlags(process.argv);
  const config = loadConfig(cfgPath, storeDirs.length > 0 ? storeDirs : undefined);

  const prefix = getFlag(rest, '--prefix') ?? '';
  const recursive = hasFlag(rest, '--recursive');

  const keys = listAllKeys(config, prefix, recursive);

  output({
    prefix: prefix || '(root)',
    recursive,
    keys,
    count: keys.length,
  });
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main().catch((err: unknown) => {
    output({ error: String(err instanceof Error ? err.message : err) });
    process.exit(1);
  });
}
