"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';
// Use the global `cell` command if available, fall back to local node script
// path resolution: dist/walls/07-runtime/cli/commands → 5 levels up → project root
const BIN = path.resolve(__dirname, '..', '..', '..', '..', '..', 'bin', 'cell.js');
// Find global cell path as fallback
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 (require('fs').existsSync(p))
                return p;
        }
        catch { }
    }
    return null;
}
// Shell-safe arg parser
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;
}
// Built-in commands that don't need to spawn child process
const BUILTINS = {
    'help': () => {
        (0, tui_1.addOutput)('Available commands:', 'info');
        (0, tui_1.addOutput)('/help, /context, /scan, /start, /stop, /status, /doctor, /vibe, /profile, /memory, /handoff, /continue, /session, /decisions, /watch, /blindspots, /sync, /cloud, /team, /community, /teach, /install-hook, /exit', '');
    },
    'clear': () => {
        (0, tui_1.addOutput)('Screen cleared', 'info');
    },
    'settings': () => {
        (0, tui_1.addOutput)('Settings: run cell setup or cell mcp-config', 'info');
        (0, tui_1.addOutput)('Cloud: cell cloud login / cell cloud sync', 'info');
    },
};
function doChatRepl() {
    (0, tui_1.startTUI)((line) => {
        const trimmed = line.startsWith('/') ? line.slice(1).trim() : line.trim();
        if (!trimmed)
            return;
        // Built-ins
        if (BUILTINS[trimmed]) {
            BUILTINS[trimmed]();
            return;
        }
        if (trimmed === 'exit' || trimmed === 'quit') {
            (0, tui_1.addOutput)('Goodbye!', 'info');
            setTimeout(() => { process.exit(0); }, 500);
            return;
        }
        // Run command via child process
        const args = parseArgs(trimmed);
        try {
            // Use the globally installed `cell` command if available, else local node script
            const globalCell = getGlobalCellPath();
            let result;
            if (globalCell) {
                result = (0, child_process_1.spawnSync)(globalCell, args, {
                    encoding: 'utf-8',
                    timeout: 30000,
                    stdio: 'pipe',
                    windowsHide: true,
                    shell: process.platform === 'win32',
                });
            }
            else if (fs.existsSync(BIN)) {
                result = (0, child_process_1.spawnSync)('node', [BIN, ...args], {
                    encoding: 'utf-8',
                    timeout: 30000,
                    stdio: 'pipe',
                    windowsHide: true,
                });
            }
            else {
                (0, tui_1.addOutput)('cell command not found. Install with: npm i -g fivocell', 'error');
                return;
            }
            const output = (result.stdout || '').replace(/████[\s\S]*?█+\n\s*\n?/g, '').trim();
            const errOut = (result.stderr || '').trim();
            if (output) {
                for (const line of output.split('\n').filter(Boolean)) {
                    (0, tui_1.addOutput)(line.replace(/^\s+/, ''));
                }
            }
            if (errOut) {
                for (const line of errOut.split('\n').filter(Boolean).slice(0, 5)) {
                    (0, tui_1.addOutput)(line, 'warn');
                }
            }
            if (!output && !errOut) {
                (0, tui_1.addOutput)('Done!', 'success');
            }
            // Health check
            try {
                const http = require('http');
                http.get('http://localhost:9876/health', { timeout: 1000 }, (res) => {
                    res.on('data', () => { });
                    res.on('end', () => { });
                }).on('error', () => { });
            }
            catch { }
        }
        catch (e) {
            (0, tui_1.addOutput)(e.message || String(e), 'error');
        }
    });
}
//# sourceMappingURL=chat-repl.js.map