"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.doChatRepl = doChatRepl;
const tui_1 = require("../tui");
const child_process_1 = require("child_process");
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const R = (s) => '\x1b[38;2;248;113;113m' + s + '\x1b[0m';
const G = (s) => '\x1b[38;2;74;222;128m' + s + '\x1b[0m';
const Y = (s) => '\x1b[38;2;251;191;36m' + s + '\x1b[0m';
// Local fallback bin path
const BIN = path.resolve(__dirname, '..', '..', '..', '..', '..', 'bin', 'cell.js');
function getGlobalCellPath() {
    const home = require('os').homedir();
    const isWin = process.platform === 'win32';
    const paths = isWin
        ? [path.join(home, 'AppData', 'Roaming', 'npm', 'cell.cmd'), path.join(home, 'AppData', 'Roaming', 'npm', 'cell')]
        : ['/usr/local/bin/cell', '/usr/bin/cell'];
    for (const p of paths) {
        try {
            if (fs.existsSync(p))
                return p;
        }
        catch { }
    }
    return null;
}
function parseArgs(line) {
    const args = [];
    let current = '';
    let inQuote = false;
    for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (ch === '"' || ch === "'") {
            inQuote = !inQuote;
        }
        else if (ch === ' ' && !inQuote) {
            if (current) {
                args.push(current);
                current = '';
            }
        }
        else {
            current += ch;
        }
    }
    if (current)
        args.push(current);
    return args;
}
// Strip ANSI codes for clean output
function stripAnsi(s) {
    return s.replace(/\x1b\[[0-9;]*m/g, '').replace(/\x1b\[[0-9;]*[A-HJKSTfg]/g, '');
}
// Run a command and return clean output
function runCommand(args) {
    const globalCell = getGlobalCellPath();
    if (globalCell) {
        // On Windows, .cmd files need cmd.exe wrapper, but we pass args as array (no shell=true)
        const isWin = process.platform === 'win32';
        const r = (0, child_process_1.spawnSync)(isWin ? 'cmd.exe' : globalCell, isWin ? ['/c', globalCell, ...args] : args, {
            encoding: 'utf-8',
            timeout: 30000,
            stdio: 'pipe',
            windowsHide: true,
            shell: false,
        });
        return { stdout: r.stdout || '', stderr: r.stderr || '', code: r.status || 0 };
    }
    if (fs.existsSync(BIN)) {
        const r = (0, child_process_1.spawnSync)('node', [BIN, ...args], {
            encoding: 'utf-8',
            timeout: 30000,
            stdio: 'pipe',
            windowsHide: true,
        });
        return { stdout: r.stdout || '', stderr: r.stderr || '', code: r.status || 0 };
    }
    return { stdout: '', stderr: 'cell command not found. Run: npm i -g fivocell', code: 1 };
}
const BUILTINS = {
    'help': () => {
        (0, tui_1.addOutput)('Available commands:', 'info');
        (0, tui_1.addOutput)(' /help    /context    /scan    /start    /stop', '');
        (0, tui_1.addOutput)(' /status  /doctor     /vibe    /profile  /memory', '');
        (0, tui_1.addOutput)(' /watch   /blindspots /sync    /cloud    /team', '');
        (0, tui_1.addOutput)(' /community  /teach  /install-hook  /exit', '');
    },
    'clear': () => {
        (0, tui_1.addOutput)('— screen cleared —', 'info');
    },
    'settings': () => {
        (0, tui_1.addOutput)('Run cell setup or cell mcp-config to configure.', 'info');
    },
};
function doChatRepl() {
    (0, tui_1.startTUI)((line) => {
        const trimmed = line.startsWith('/') ? line.slice(1).trim() : line.trim();
        if (!trimmed)
            return;
        // Show what user asked — clean prompt format
        (0, tui_1.addPrompt)(trimmed);
        if (BUILTINS[trimmed]) {
            BUILTINS[trimmed]();
            return;
        }
        if (trimmed === 'exit' || trimmed === 'quit') {
            (0, tui_1.addOutput)('Goodbye!', 'info');
            setTimeout(() => { process.exit(0); }, 500);
            return;
        }
        const args = parseArgs(trimmed);
        try {
            const result = runCommand(args);
            // Clean output: strip FIGlet banner, strip ANSI, dedupe empty lines
            let out = stripAnsi(result.stdout);
            // Remove FIGlet banner (lines with ███ or ╔═)
            out = out.split('\n').filter(l => !l.match(/^[█╔╚║─=]+$/) && l.length > 0).join('\n').trim();
            // Remove "  $ cell <command>" footer if present
            out = out.replace(/\$ cell <command>.*$/m, '').trim();
            if (out) {
                for (const line of out.split('\n')) {
                    if (line.trim())
                        (0, tui_1.addOutput)(line);
                }
            }
            else if (result.stderr) {
                (0, tui_1.addOutput)(stripAnsi(result.stderr).split('\n').filter(l => l.trim()).slice(0, 3).join(' | '), 'warn');
            }
            else {
                (0, tui_1.addOutput)('Done.', 'success');
            }
        }
        catch (e) {
            (0, tui_1.addOutput)(e.message || String(e), 'error');
        }
    });
}
//# sourceMappingURL=chat-repl.js.map