/**
 * `ai-governance discover` subcommand.
 *
 * Wires runDiscoveryCli (src/governance/discovery-cli.ts) into the
 * customer-facing CLI binary. Closes the W2.1 customer-visible loop —
 * `npx @connexum/ai-governance discover` actually exists and runs now.
 *
 * Usage:
 *   ai-governance discover --root <path>
 *                          --org-id <org>
 *                          --key <pem-private-key-path>
 *                          --endpoint <https://...>
 *                          [--dry-run]
 *                          [--max-depth <n>]
 *
 * Exit codes:
 *   0  all manifests pushed (or dry-run completed)
 *   1  one or more manifests failed to push
 *   2  argument error
 *
 * @connexum/ai-governance  Discovery CLI integration
 */
import * as fs from 'node:fs';
import * as crypto from 'node:crypto';
import { runDiscoveryCli, formatCliReport } from '../governance/discovery-cli.js';
function parseDiscoverArgs(args) {
    const out = { dryRun: false, help: false };
    for (let i = 0; i < args.length; i++) {
        const a = args[i];
        if (a === '--root')
            out.root = args[++i];
        else if (a === '--org-id')
            out.orgId = args[++i];
        else if (a === '--key')
            out.keyPath = args[++i];
        else if (a === '--endpoint')
            out.endpoint = args[++i];
        else if (a === '--dry-run')
            out.dryRun = true;
        else if (a === '--max-depth')
            out.maxDepth = parseInt(args[++i], 10);
        else if (a === '--help' || a === '-h')
            out.help = true;
        else if (a.startsWith('--')) {
            throw new Error(`unknown flag '${a}'`);
        }
    }
    return out;
}
const HELP = `
ai-governance discover — scan a project for agents and push signed manifests

Usage:
  ai-governance discover --root <path> --org-id <org> --key <pem-path> --endpoint <url> [--dry-run]

Flags:
  --root <path>         Project directory to scan (required)
  --org-id <org>        Organisation identifier (required)
  --key <pem-path>      Ed25519 private key in PEM format (required unless --dry-run)
  --endpoint <url>      Manifest receive endpoint (required unless --dry-run uses placeholder)
  --dry-run             Discover + report; do NOT sign or push
  --max-depth <n>       Maximum directory recursion depth (default 8)
  --help, -h            Show this help

Exit codes:
  0  All manifests pushed successfully (or dry-run completed)
  1  One or more pushes failed
  2  Argument or configuration error

Honors Locked Invariant 10 (push-only): the scan runs entirely on your
machine; nothing leaves until you explicitly push.
`.trimStart();
export async function runDiscoverCommand(args) {
    let parsed;
    try {
        parsed = parseDiscoverArgs(args);
    }
    catch (err) {
        process.stderr.write(`Error: ${err.message}\nRun 'ai-governance discover --help' for usage.\n`);
        return 2;
    }
    if (parsed.help) {
        process.stdout.write(HELP);
        return 0;
    }
    if (!parsed.root) {
        process.stderr.write("Error: --root is required.\nRun 'ai-governance discover --help'.\n");
        return 2;
    }
    if (!parsed.orgId) {
        process.stderr.write("Error: --org-id is required.\nRun 'ai-governance discover --help'.\n");
        return 2;
    }
    let privateKey;
    let endpoint = parsed.endpoint ?? 'https://proxy.my-cc.io/api/v1/manifests';
    if (parsed.dryRun) {
        // Synthesize a throwaway key — never used because dry-run skips signing+push.
        privateKey = crypto.generateKeyPairSync('ed25519').privateKey;
    }
    else {
        if (!parsed.keyPath) {
            process.stderr.write("Error: --key is required (or use --dry-run).\n");
            return 2;
        }
        if (!parsed.endpoint) {
            process.stderr.write("Error: --endpoint is required (or use --dry-run).\n");
            return 2;
        }
        let pem;
        try {
            pem = fs.readFileSync(parsed.keyPath, 'utf8');
        }
        catch (err) {
            process.stderr.write(`Error: cannot read --key ${parsed.keyPath}: ${err.message}\n`);
            return 2;
        }
        try {
            privateKey = crypto.createPrivateKey({ key: pem, format: 'pem' });
        }
        catch (err) {
            process.stderr.write(`Error: invalid PEM private key: ${err.message}\n`);
            return 2;
        }
    }
    let result;
    try {
        result = await runDiscoveryCli({
            rootDir: parsed.root,
            orgId: parsed.orgId,
            privateKey,
            endpoint,
            discovery: parsed.maxDepth ? { maxDepth: parsed.maxDepth } : undefined,
            dryRun: parsed.dryRun,
        });
    }
    catch (err) {
        process.stderr.write(`Error: ${err.message}\n`);
        return 2;
    }
    process.stdout.write(formatCliReport(result) + '\n');
    return result.ok ? 0 : 1;
}
//# sourceMappingURL=discover.js.map