"use strict";
// src/orchestrator/story/adapters/GeminiAdapter.ts
// v1.17.0 — Spawns the Google `gemini` CLI for non-interactive completion.
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeminiAdapter = void 0;
const child_process_1 = require("child_process");
const util_1 = require("util");
const child_process_2 = require("child_process");
const execFileP = (0, util_1.promisify)(child_process_2.execFile);
class GeminiAdapter {
    name = 'gemini';
    async isAvailable() {
        try {
            await execFileP('gemini', ['--version'], { timeout: 5_000 });
            return true;
        }
        catch {
            return false;
        }
    }
    async invoke(prompt, opts = {}) {
        const start = Date.now();
        const timeoutMs = opts.timeoutMs ?? 300_000;
        // Gemini CLI prompt syntax: pass via stdin with --prompt - flag, OR via -p.
        const args = [];
        if (opts.model)
            args.push('--model', opts.model);
        let stdout = '';
        let stderr = '';
        let exitCode = -1;
        let timedOut = false;
        try {
            await new Promise((resolve, reject) => {
                const child = (0, child_process_1.spawn)('gemini', args, {
                    cwd: opts.cwd || process.cwd(),
                    env: { ...process.env, ...(opts.env || {}) },
                    stdio: ['pipe', 'pipe', 'pipe'],
                });
                const t = setTimeout(() => {
                    timedOut = true;
                    try {
                        child.kill('SIGTERM');
                    }
                    catch { /* */ }
                    setTimeout(() => { try {
                        child.kill('SIGKILL');
                    }
                    catch { /* */ } }, 2000).unref();
                }, timeoutMs);
                if (typeof t.unref === 'function')
                    t.unref();
                child.stdout?.on('data', (c) => { stdout += String(c); });
                child.stderr?.on('data', (c) => { stderr += String(c); });
                child.on('error', (err) => { clearTimeout(t); reject(err); });
                child.on('exit', (code) => {
                    clearTimeout(t);
                    exitCode = typeof code === 'number' ? code : -1;
                    resolve();
                });
                child.stdin?.write(prompt);
                child.stdin?.end();
            });
        }
        catch (err) {
            return {
                ok: false,
                text: stdout,
                exitCode: -1,
                durationMs: Date.now() - start,
                adapter: this.name,
                error: `spawn_error: ${err instanceof Error ? err.message : String(err)}; stderr: ${stderr.slice(0, 200)}`,
            };
        }
        // Gemini CLI may emit prefatory log lines; pull the JSON envelope if present.
        let structured;
        try {
            const jsonStart = stdout.indexOf('{');
            if (jsonStart >= 0)
                structured = JSON.parse(stdout.slice(jsonStart));
        }
        catch { /* leave undefined */ }
        return {
            ok: exitCode === 0 && !timedOut,
            text: stdout,
            structured,
            exitCode,
            durationMs: Date.now() - start,
            adapter: this.name,
            error: timedOut ? `timeout_after_${timeoutMs}ms` : (exitCode !== 0 ? `exit_${exitCode}: ${stderr.slice(0, 200)}` : undefined),
        };
    }
}
exports.GeminiAdapter = GeminiAdapter;
