/**
 * Claude Code Executor Service
 *
 * Infrastructure implementation of IAgentExecutor for Claude Code agent.
 * Executes prompts via the `claude` CLI subprocess with JSON and stream-json
 * output formats.
 *
 * Uses constructor dependency injection for the spawn function
 * to enable testability without mocking node:child_process directly.
 */
/** Features supported by Claude Code CLI */
const SUPPORTED_FEATURES = new Set([
    'session-resume',
    'streaming',
    'system-prompt',
    'structured-output',
]);
/**
 * Executor service for Claude Code agent.
 * Uses subprocess spawning to interact with the `claude` CLI.
 */
export class ClaudeCodeExecutorService {
    spawn;
    agentType = 'claude-code';
    /** When true, suppresses debug logging (set per-call via options.silent) */
    silent = false;
    constructor(spawn) {
        this.spawn = spawn;
    }
    /** Debug logging — writes to stdout so it appears in the worker log file */
    log(message) {
        if (this.silent)
            return;
        const ts = new Date().toISOString();
        process.stdout.write(`[${ts}] [claude-executor] ${message}\n`);
    }
    async execute(prompt, options) {
        this.silent = options?.silent ?? false;
        // Use stream-json so we get real-time events in the worker log
        // instead of zero output for minutes with --output-format json
        const args = this.buildStreamArgs(prompt, options);
        const spawnOpts = this.buildSpawnOptions(options);
        this.log(`Spawning: claude ${args.map((a) => (a.length > 80 ? `${a.slice(0, 77)}...` : a)).join(' ')}`);
        this.log(`Spawn options: ${JSON.stringify(spawnOpts)}`);
        const proc = this.spawn('claude', args, spawnOpts);
        this.log(`Subprocess PID: ${proc.pid ?? 'undefined (spawn may have failed)'}`);
        // Close stdin immediately — we pass the prompt via -p, not stdin.
        if (proc.stdin) {
            proc.stdin.end();
        }
        return new Promise((resolve, reject) => {
            // Line-based parsing: only keep the data we need, not all of stdout
            let lineBuffer = '';
            let stderr = '';
            let timedOut = false;
            let timeoutId;
            // Collected from the stream — only the final result line matters
            let resultText = '';
            let sessionId;
            let usage;
            let metadata;
            if (options?.timeout) {
                timeoutId = setTimeout(() => {
                    timedOut = true;
                    proc.kill();
                }, options.timeout);
            }
            const processLine = (line) => {
                this.logStreamEvent(line);
                try {
                    const parsed = JSON.parse(line);
                    if (parsed.type === 'result') {
                        resultText = parsed.result ?? '';
                        if (parsed.session_id)
                            sessionId = parsed.session_id;
                        if (parsed.input_tokens !== undefined && parsed.output_tokens !== undefined) {
                            usage = { inputTokens: parsed.input_tokens, outputTokens: parsed.output_tokens };
                        }
                        const { type: _t, result: _r, session_id: _s, input_tokens: _it, output_tokens: _ot, ...rest } = parsed;
                        if (Object.keys(rest).length > 0)
                            metadata = rest;
                    }
                }
                catch {
                    /* not JSON — already logged by logStreamEvent */
                }
            };
            proc.stdout?.on('data', (chunk) => {
                lineBuffer += chunk.toString();
                const lines = lineBuffer.split('\n');
                lineBuffer = lines.pop() ?? '';
                for (const line of lines) {
                    const trimmed = line.trim();
                    if (trimmed)
                        processLine(trimmed);
                }
            });
            proc.stderr?.on('data', (chunk) => {
                const data = chunk.toString();
                stderr += data;
                this.log(`stderr: ${data.trimEnd()}`);
            });
            proc.on('error', (error) => {
                this.log(`Process error event: ${error.message}`);
                if (timeoutId)
                    clearTimeout(timeoutId);
                reject(error);
            });
            proc.on('close', (code) => {
                // Flush remaining buffer
                if (lineBuffer.trim())
                    processLine(lineBuffer.trim());
                this.log(`Process closed with code ${code}, result=${resultText.length} chars`);
                if (timeoutId)
                    clearTimeout(timeoutId);
                if (timedOut) {
                    reject(new Error('Agent execution timed out'));
                    return;
                }
                if (code !== 0 && code !== null) {
                    reject(new Error(stderr.trim() || `Process exited with code ${code}`));
                    return;
                }
                const result = { result: resultText };
                if (sessionId)
                    result.sessionId = sessionId;
                if (usage)
                    result.usage = usage;
                if (metadata)
                    result.metadata = metadata;
                resolve(result);
            });
        });
    }
    async *executeStream(prompt, options) {
        const args = this.buildStreamArgs(prompt, options);
        const spawnOpts = this.buildSpawnOptions(options);
        const proc = this.spawn('claude', args, spawnOpts);
        // Close stdin immediately - we're not sending input in print mode
        if (proc.stdin) {
            proc.stdin.end();
        }
        // Buffer for incomplete lines
        let lineBuffer = '';
        let stderr = '';
        // Create an async queue to bridge event-based IO to async iteration
        const queue = [];
        let resolve = null;
        let error = null;
        function enqueue(event) {
            queue.push(event);
            if (resolve) {
                resolve();
                resolve = null;
            }
        }
        function waitForItem() {
            if (queue.length > 0)
                return Promise.resolve();
            return new Promise((r) => {
                resolve = r;
            });
        }
        proc.stdout?.on('data', (chunk) => {
            lineBuffer += chunk.toString();
            const lines = lineBuffer.split('\n');
            // Keep the last partial line in the buffer
            lineBuffer = lines.pop() ?? '';
            for (const line of lines) {
                const trimmed = line.trim();
                if (!trimmed)
                    continue;
                const event = this.parseStreamLine(trimmed);
                if (event) {
                    enqueue(event);
                }
            }
        });
        proc.stderr?.on('data', (chunk) => {
            stderr += chunk.toString();
        });
        proc.on('error', (err) => {
            error = err;
            enqueue(null); // signal end
        });
        proc.on('close', (code) => {
            // Process any remaining data in the buffer
            if (lineBuffer.trim()) {
                const event = this.parseStreamLine(lineBuffer.trim());
                if (event)
                    enqueue(event);
            }
            if (code !== 0 && code !== null && stderr.trim()) {
                enqueue({
                    type: 'error',
                    content: stderr.trim(),
                    timestamp: new Date(),
                });
            }
            enqueue(null); // signal end
        });
        // Yield events as they arrive
        while (true) {
            await waitForItem();
            const item = queue.shift();
            if (item === null || item === undefined) {
                if (error !== null) {
                    yield {
                        type: 'error',
                        content: error.message,
                        timestamp: new Date(),
                    };
                }
                return;
            }
            yield item;
        }
    }
    /**
     * Log a stream-json line as a human-readable event in the worker log.
     * Extracts tool calls, assistant text, and result summaries.
     */
    logStreamEvent(line) {
        try {
            const parsed = JSON.parse(line);
            // Assistant messages contain tool_use and text blocks
            if (parsed.type === 'assistant' && Array.isArray(parsed.message?.content)) {
                for (const block of parsed.message.content) {
                    if (block.type === 'tool_use') {
                        const inputJson = JSON.stringify(block.input ?? {});
                        this.log(`[tool] ${block.name} ${inputJson}`);
                    }
                    else if (block.type === 'text' && block.text?.trim()) {
                        this.log(`[text] ${block.text.trim().replace(/\n/g, ' ')}`);
                    }
                }
                return;
            }
            // Final result — summary with session and token info
            if (parsed.type === 'result') {
                this.log(`[result] ${(parsed.result ?? '').length} chars, session=${parsed.session_id ?? 'none'}`);
                if (parsed.input_tokens != null) {
                    this.log(`[tokens] ${parsed.input_tokens} in / ${parsed.output_tokens} out`);
                }
                return;
            }
        }
        catch {
            // Non-JSON line — log it raw
            if (line.length > 0) {
                this.log(`[raw] ${line}`);
            }
        }
    }
    supportsFeature(feature) {
        return SUPPORTED_FEATURES.has(feature);
    }
    buildArgs(prompt, options) {
        const args = ['-p', prompt, '--output-format', 'json', '--dangerously-skip-permissions'];
        if (options?.resumeSession)
            args.push('--resume', options.resumeSession);
        if (options?.model)
            args.push('--model', options.model);
        if (options?.systemPrompt)
            args.push('--append-system-prompt', options.systemPrompt);
        if (options?.allowedTools?.length)
            args.push('--allowedTools', options.allowedTools.join(','));
        if (options?.outputSchema)
            args.push('--json-schema', JSON.stringify(options.outputSchema));
        if (options?.maxTurns)
            args.push('--max-turns', String(options.maxTurns));
        return args;
    }
    buildStreamArgs(prompt, options) {
        const args = this.buildArgs(prompt, options);
        const fmtIdx = args.indexOf('--output-format');
        if (fmtIdx !== -1)
            args[fmtIdx + 1] = 'stream-json';
        // stream-json requires --verbose and --include-partial-messages when using -p (--print)
        // --no-chrome ensures it runs in non-interactive mode without browser integration
        args.push('--verbose', '--include-partial-messages', '--no-chrome');
        return args;
    }
    buildSpawnOptions(options) {
        const spawnOpts = {};
        if (options?.cwd)
            spawnOpts.cwd = options.cwd;
        return spawnOpts;
    }
    parseJsonResult(stdout) {
        const trimmed = stdout.trim();
        try {
            const parsed = JSON.parse(trimmed);
            const result = {
                result: parsed.result ?? trimmed,
            };
            if (parsed.session_id) {
                result.sessionId = parsed.session_id;
            }
            if (parsed.input_tokens !== undefined && parsed.output_tokens !== undefined) {
                result.usage = {
                    inputTokens: parsed.input_tokens,
                    outputTokens: parsed.output_tokens,
                };
            }
            // Store additional metadata
            const { result: _r, session_id: _s, input_tokens: _it, output_tokens: _ot, ...rest } = parsed;
            if (Object.keys(rest).length > 0) {
                result.metadata = rest;
            }
            return result;
        }
        catch {
            // If stdout is not valid JSON, treat it as raw text result
            return { result: trimmed };
        }
    }
    parseStreamLine(line) {
        try {
            const parsed = JSON.parse(line);
            // Handle Claude Code stream_json format with nested events
            if (parsed.type === 'stream_event' && parsed.event) {
                const { event } = parsed;
                // Extract text deltas for progress
                if (event.type === 'content_block_delta' && event.delta?.text) {
                    return {
                        type: 'progress',
                        content: event.delta.text,
                        timestamp: new Date(),
                    };
                }
                // Message complete - ignore for now (accumulated text is in progress events)
                if (event.type === 'message_stop') {
                    return null;
                }
            }
            // Ignore assistant messages - we already get all text via content_block_delta events
            if (parsed.type === 'assistant') {
                return null;
            }
            // Handle legacy format (backward compatibility)
            if (parsed.type === 'result') {
                return {
                    type: 'result',
                    content: parsed.result ?? '',
                    timestamp: new Date(),
                };
            }
            if (parsed.type === 'error') {
                return {
                    type: 'error',
                    content: parsed.error ?? parsed.message ?? '',
                    timestamp: new Date(),
                };
            }
            // Generic progress for other event types (ensure content is a string)
            if (parsed.content || parsed.message) {
                const rawContent = parsed.content ?? parsed.message;
                const content = typeof rawContent === 'string' ? rawContent : JSON.stringify(rawContent);
                return {
                    type: 'progress',
                    content,
                    timestamp: new Date(),
                };
            }
            return null;
        }
        catch {
            // Non-JSON line, treat as progress text
            return {
                type: 'progress',
                content: line,
                timestamp: new Date(),
            };
        }
    }
}
