"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileCommand = compileCommand;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const ora_1 = __importDefault(require("ora"));
const durable_compiler_1 = require("../../services/yaml-workflow/durable-compiler");
const llm_1 = require("../../services/llm");
const scanner_1 = require("./scanner");
const output_1 = require("./output");
// ── Orchestrator ─────────────────────────────────────────────────────────
async function compileCommand(target, options) {
    const model = options.model || process.env.LT_LLM_MODEL_PRIMARY || 'claude-sonnet-4-6';
    const quiet = !!options.quiet;
    // 1. Validate LLM API key
    if (!(0, llm_1.hasLLMApiKey)(model)) {
        if (!quiet) {
            console.error(picocolors_1.default.red('\n  No LLM API key found.'));
            console.error(picocolors_1.default.dim('  Set ANTHROPIC_API_KEY or OPENAI_API_KEY in your environment.'));
            console.error(picocolors_1.default.dim('  Or create a .env file in the current directory:\n'));
            console.error(picocolors_1.default.dim('    ANTHROPIC_API_KEY=sk-ant-...\n'));
        }
        process.exit(1);
    }
    // 2. Resolve target path
    const resolved = resolveTarget(target, quiet);
    // 3. Discover workflows
    const workflows = discoverWorkflows(resolved, options.function, quiet);
    if (workflows.length === 0) {
        if (!quiet)
            console.log(picocolors_1.default.yellow('\n  No workflow files found.\n'));
        process.exit(0);
    }
    // 4. Dry run — show discoveries and exit
    if (options.dryRun) {
        if (!quiet)
            (0, output_1.printDiscovery)(workflows);
        return;
    }
    // 5. Compile each workflow
    if (!quiet)
        console.log();
    const t0 = Date.now();
    let compiled = 0;
    for (const wf of workflows) {
        compiled += await compileOne(wf.path, wf.relativePath, wf.functionName, model, quiet, options.output)
            ? 1 : 0;
    }
    // 6. Summary
    if (!quiet)
        (0, output_1.printSummary)(compiled, Date.now() - t0);
    if (compiled < workflows.length) {
        process.exit(1);
    }
}
// ── Helpers ──────────────────────────────────────────────────────────────
function resolveTarget(target, quiet) {
    const resolved = path.resolve(target || '.');
    if (!fs.existsSync(resolved)) {
        if (!quiet)
            console.error(picocolors_1.default.red(`\n  Not found: ${resolved}\n`));
        process.exit(1);
    }
    const stat = fs.statSync(resolved);
    return { type: stat.isDirectory() ? 'directory' : 'file', path: resolved };
}
function discoverWorkflows(resolved, functionFilter, quiet) {
    if (resolved.type === 'file') {
        const baseDir = path.dirname(resolved.path);
        const wf = (0, scanner_1.analyzeFile)(resolved.path, baseDir, functionFilter);
        if (!wf) {
            if (!quiet)
                console.log(picocolors_1.default.yellow(`\n  ${path.basename(resolved.path)} does not appear to be a durable workflow.\n`));
            process.exit(0);
        }
        return [wf];
    }
    return (0, scanner_1.scanForWorkflows)(resolved.path, functionFilter);
}
async function compileOne(filePath, relativePath, functionName, model, quiet, outputDir) {
    const modelShort = model.replace(/^claude-/, '').replace(/^gpt-/, '');
    const spinner = quiet
        ? null
        : (0, ora_1.default)({
            text: `Compiling ${picocolors_1.default.bold(relativePath)} ${picocolors_1.default.dim(`(${functionName} · ${modelShort})`)}`,
            indent: 2,
        }).start();
    try {
        const result = await (0, durable_compiler_1.compileDurableToYaml)({
            source: filePath,
            isFilePath: true,
            workflowName: functionName,
            name: functionName,
        });
        const outputPath = (0, output_1.resolveOutputPath)(filePath, outputDir);
        (0, output_1.writeCompiledYaml)(outputPath, result, filePath, functionName, model);
        const outputRelative = path.relative(process.cwd(), outputPath);
        spinner?.stop();
        if (!quiet)
            (0, output_1.printCompiled)(relativePath, outputRelative, result);
        return true;
    }
    catch (err) {
        spinner?.stop();
        if (!quiet)
            (0, output_1.printError)(relativePath, formatCompileError(err));
        return false;
    }
}
function formatCompileError(err) {
    const msg = err.message || String(err);
    // LLM API errors
    if (msg.includes('401') || msg.includes('authentication')) {
        return 'API key rejected — check ANTHROPIC_API_KEY or OPENAI_API_KEY';
    }
    if (msg.includes('429') || msg.includes('rate limit')) {
        return 'Rate limited — wait a moment and retry';
    }
    if (msg.includes('Failed to get valid JSON')) {
        return 'LLM returned invalid output after 3 attempts — try a different model with --model';
    }
    // File errors
    if (msg.includes('ENOENT')) {
        return `File not found: ${msg.split("'").at(1) || msg}`;
    }
    // Truncate long errors
    return msg.length > 200 ? msg.slice(0, 200) + '...' : msg;
}
