#!/usr/bin/env node
import React from 'react';
import { render } from 'ink';
import { loadConfig } from './config.js';
import { App } from './ui/App.js';
import { runPrintMode } from './print.js';
import { connectMcpServers } from './mcp/client.js';
import { createHookRunner } from './hooks.js';
import { loadSession } from './sessions.js';
function parseArgs(argv) {
    const args = {
        print: null,
        model: null,
        yolo: false,
        cwd: process.cwd(),
        help: false,
        continueSession: false,
    };
    for (let i = 0; i < argv.length; i++) {
        const a = argv[i];
        switch (a) {
            case '-p':
            case '--print':
                args.print = argv[++i] ?? '';
                break;
            case '-m':
            case '--model':
                args.model = argv[++i] ?? null;
                break;
            case '--yolo':
                args.yolo = true;
                break;
            case '-c':
            case '--continue':
                args.continueSession = true;
                break;
            case '--cwd':
                args.cwd = argv[++i] ?? process.cwd();
                break;
            case '-h':
            case '--help':
                args.help = true;
                break;
            default:
                // Bare argument in print position: treat `cheapcode "do x"` as one-shot.
                if (!a.startsWith('-') && args.print === null && !process.stdout.isTTY) {
                    args.print = a;
                }
        }
    }
    return args;
}
const USAGE = `cheapcode - open-source CLI coding agent on OpenRouter

usage:
  cheapcode                    interactive session in the current directory
  cheapcode -p "prompt"        one-shot: run a task and print the result
  cheapcode --yolo -p "..."    one-shot with all tool approvals skipped

options:
  -m, --model <id>   OpenRouter model id (default: from config, else openrouter/auto)
  -c, --continue     resume the saved session for this directory
  --cwd <dir>        working directory for the session
  --yolo             auto-approve all tool calls (use with care)
  -h, --help         show this help

setup:
  export CHEAPCODE_API_KEY=cc-sk-...     (create one at https://cheapcode.ai/account,
                                          or put "apiKey" in ~/.config/cheapcode/config.json)

config (~/.config/cheapcode/config.json, project .cheapcode/settings.json):
  { "apiKey": "...", "model": "...",
    "mcpServers": { "name": { "command": "...", "args": [] } },
    "hooks": { "preToolUse": "cmd", "postToolUse": "cmd" } }`;
async function main() {
    const args = parseArgs(process.argv.slice(2));
    if (args.help) {
        console.log(USAGE);
        return;
    }
    const config = loadConfig(args.cwd);
    const apiKey = config.apiKey;
    if (!apiKey) {
        console.error('No API key found.\nSet CHEAPCODE_API_KEY (create one at https://cheapcode.ai/account)\nor add "apiKey" to ~/.config/cheapcode/config.json');
        process.exit(1);
    }
    let model = args.model ?? config.model;
    // --continue restores the saved session for this directory (and its model,
    // unless one was given explicitly).
    let initialMessages;
    if (args.continueSession) {
        const session = loadSession(args.cwd);
        if (session) {
            initialMessages = session.messages;
            if (!args.model && session.model)
                model = session.model;
        }
        else {
            console.error('warning: no saved session for this directory; starting fresh');
        }
    }
    // Connect configured MCP servers (failures warn, never block startup).
    let mcpClients = [];
    let mcpTools = [];
    if (Object.keys(config.mcpServers).length > 0) {
        const connected = await connectMcpServers(config.mcpServers, (msg) => console.error(`warning: ${msg}`));
        mcpClients = connected.clients;
        mcpTools = connected.tools;
    }
    const cleanup = () => {
        for (const c of mcpClients)
            c.close();
    };
    process.on('exit', cleanup);
    const hooks = createHookRunner(config.hooks, args.cwd);
    if (args.print !== null) {
        const code = await runPrintMode({
            apiKey,
            model,
            provider: config.provider,
            cwd: args.cwd,
            prompt: args.print,
            yolo: args.yolo,
            mcpTools,
            hooks,
            initialMessages,
        });
        cleanup();
        process.exit(code);
    }
    if (!process.stdin.isTTY) {
        console.error('Interactive mode needs a TTY. Use -p "prompt" for one-shot mode.');
        process.exit(1);
    }
    render(React.createElement(App, {
        apiKey,
        provider: config.provider,
        initialModel: model,
        cwd: args.cwd,
        yolo: args.yolo,
        mcpTools,
        mcpServerNames: mcpClients.map((c) => c.serverName),
        hooks,
        initialMessages,
    }), { exitOnCtrlC: true });
}
main().catch((err) => {
    console.error(err instanceof Error ? err.message : String(err));
    process.exit(1);
});
