#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// retrieve.ts — Retrieve a prepared prompt by ID
//
// Part of: .opencode/skills/templating-vault/scripts/
//
// Returns the full rendered prompt text and variable schema for a prepared
// prompt stored by render.ts --prepare. The subagent uses this to understand
// its instructions and determine which variables need regex extraction.
//
// USAGE:
//   retrieve.ts --id <id> [--config <path>] [--store-dir <path>]
//
// OUTPUT (stdout): JSON with content, schema, and template reference
// =============================================================================
import { fileURLToPath } from 'node:url';
import {
  parseCommonFlags, getFlag, output,
  loadConfig, readValue,
} 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 id = getFlag(rest, '--id');

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

  const preparedKey = `prepared.${id}`;
  const content = readValue(config, preparedKey);

  if (content === null) {
    output({ found: false, error: `Prepared prompt "${id}" not found in vault`, id });
    process.exit(1);
  }

  // Load schema if available
  const schemaKey = `prepared.${id}.schema`;
  const schemaRaw = readValue(config, schemaKey);
  let variables: Record<string, unknown> = {};
  if (schemaRaw) {
    try {
      const schema = JSON.parse(schemaRaw);
      variables = schema.variables ?? {};
    } catch {
      // ignore parse errors
    }
  }

  // Load template reference
  const refKey = `prepared.${id}.template_ref`;
  const templateRef = readValue(config, refKey);

  output({
    found: true,
    id,
    template_key: templateRef ?? null,
    content,
    variables,
  });
}

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);
  });
}
