import { spawn } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import chalk from 'chalk';
const DEFAULT_V4_AGENT_DIR_UNIX = '/var/www/V4-Operating-Agent';
export function defaultV4PythonBin() {
    return process.env.VIGTHORIA_V4_PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
}
export function defaultV4AgentDir() {
    if (process.env.VIGTHORIA_V4_AGENT_DIR) {
        return process.env.VIGTHORIA_V4_AGENT_DIR;
    }
    // The historical hardcoded default only ever existed on this project's Linux
    // dev/test boxes. Never assume it on Windows/macOS — only use it as a
    // fallback when it actually exists on disk, so real users get a clear
    // "not found" error instead of a silently-wrong path.
    if (process.platform !== 'win32' && fs.existsSync(DEFAULT_V4_AGENT_DIR_UNIX)) {
        return DEFAULT_V4_AGENT_DIR_UNIX;
    }
    return undefined;
}
export class V4Command {
    _config;
    logger;
    constructor(_config, logger) {
        this._config = _config;
        this.logger = logger;
    }
    register(program) {
        program
            .command('v4')
            .alias('v4-agent')
            .description('Launch Vigthoria V4 Operating Agent (DeerFlow 2.0 harness)')
            .option('--provider <provider>', 'Provider: cloud | v3_local | byok')
            .option('--api-key <key>', 'BYOK API key for non-interactive mode')
            .option('--base-url <url>', 'Provider base URL override')
            .option('--model <name>', 'Provider model override')
            .option('--transport <mode>', 'Bridge transport: auto | ws | sse', 'auto')
            .option('--harness-stream-url <url>', 'Override harness stream URL')
            .option('--harness-control-url <url>', 'Override harness control URL')
            .option('--gateway-url <url>', 'DeerFlow Gateway URL')
            .option('--prompt <text>', 'Task prompt to execute')
            .option('--workspace <path>', 'Workspace path', process.cwd())
            .option('--session-id <id>', 'Explicit V4 session id')
            .option('--non-interactive', 'Disable interactive menu and use CLI options', false)
            .option('--python <bin>', 'Python binary to use', defaultV4PythonBin())
            .option('--v4-path <path>', 'V4 agent root path (or set VIGTHORIA_V4_AGENT_DIR)', defaultV4AgentDir())
            .action(async (options) => {
            await this.run(options);
        });
    }
    async run(options) {
        const resolvedV4Path = options.v4Path || defaultV4AgentDir();
        if (!resolvedV4Path) {
            throw Object.assign(new Error('V4 agent path not set. Pass --v4-path <dir> or set the VIGTHORIA_V4_AGENT_DIR environment variable.'), { skipPathScrub: true });
        }
        const v4Path = path.resolve(String(resolvedV4Path));
        const pythonBin = String(options.python || defaultV4PythonBin());
        const mainScript = path.join(v4Path, 'main_agent.py');
        if (!fs.existsSync(mainScript)) {
            throw Object.assign(new Error(`V4 launcher not found: ${mainScript}. Check --v4-path/VIGTHORIA_V4_AGENT_DIR points at a valid V4-Operating-Agent checkout.`), { skipPathScrub: true });
        }
        const args = [mainScript];
        if (options.nonInteractive) {
            args.push('--non-interactive');
        }
        if (options.provider) {
            args.push('--provider', String(options.provider));
        }
        if (options.apiKey) {
            args.push('--api-key', String(options.apiKey));
        }
        if (options.baseUrl) {
            args.push('--base-url', String(options.baseUrl));
        }
        if (options.model) {
            args.push('--model', String(options.model));
        }
        if (options.transport) {
            args.push('--transport', String(options.transport));
        }
        if (options.harnessStreamUrl) {
            args.push('--harness-stream-url', String(options.harnessStreamUrl));
        }
        if (options.harnessControlUrl) {
            args.push('--harness-control-url', String(options.harnessControlUrl));
        }
        if (options.gatewayUrl) {
            args.push('--gateway-url', String(options.gatewayUrl));
        }
        if (options.prompt) {
            args.push('--prompt', String(options.prompt));
        }
        if (options.workspace) {
            args.push('--workspace', path.resolve(String(options.workspace)));
        }
        if (options.sessionId) {
            args.push('--session-id', String(options.sessionId));
        }
        this.logger.info(chalk.cyan(`Launching V4 Operating Agent from ${v4Path}`));
        const child = spawn(pythonBin, args, {
            cwd: v4Path,
            stdio: 'inherit',
            env: {
                ...process.env,
                PYTHONUNBUFFERED: '1',
            },
        });
        const exitCode = await new Promise((resolve, reject) => {
            child.on('error', reject);
            child.on('close', (code) => resolve(code ?? 1));
        });
        if (exitCode !== 0) {
            throw new Error(`V4 agent exited with status ${exitCode}`);
        }
    }
}
