#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// get.ts — Retrieve a value from the vault
//
// Part of: .opencode/skills/templating-vault/scripts/
//
// Reads a value by key. If the key is marked template: true, evaluates the
// Nunjucks expression lazily, resolving dependencies from the vault.
//
// USAGE:
//   get.ts --key <key> [--config <path>] [--store-dir <path>]
//   get.ts --prefix <prefix> [--config <path>] [--store-dir <path>]
//
// With --prefix: returns all key-value pairs under the prefix.
//
// OUTPUT (stdout): JSON result
// =============================================================================
import { fileURLToPath } from 'node:url';
import {
  parseCommonFlags, getFlag, output,
  loadConfig, getValue, 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 key = getFlag(rest, '--key');
  const prefix = getFlag(rest, '--prefix');

  if (!key && !prefix) {
    output({ found: false, error: '--key or --prefix is required' });
    process.exit(1);
  }

  if (key) {
    const result = getValue(config, key);
    output(result);
  } else if (prefix) {
    const keys = listAllKeys(config, prefix, true);
    const entries: Record<string, string> = {};
    for (const k of keys) {
      const result = getValue(config, k);
      if (result.found) {
        entries[k] = result.value;
      }
    }
    output({ prefix, entries, count: Object.keys(entries).length });
  }
}

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