"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.doStart = doStart;
exports.doStop = doStop;
exports.doRun = doRun;
exports.doSetup = doSetup;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const figlet_1 = __importDefault(require("figlet"));
const gradient_string_1 = __importDefault(require("gradient-string"));
const utils_1 = require("../utils");
const project = (0, utils_1.getProjectName)();
function doStart(args) {
    const fromAutostart = args.includes('--from-autostart');
    if (fromAutostart) {
        console.log('[cell] Autostart: starting daemon...');
    }
    else {
        const banner = figlet_1.default.textSync('FivoCell', { font: 'ANSI Shadow', horizontalLayout: 'fitted' });
        console.log((0, gradient_string_1.default)(['#FF6B35', '#FFAB91'])(banner));
        (0, utils_1.printDim)('Starting everything...\n');
        try {
            const { registerAutostart } = require('../../setup/autostart');
            const auto = registerAutostart();
            if (auto.ok && !auto.skipped)
                (0, utils_1.printSuccess)(auto.message);
            else if (!auto.ok)
                (0, utils_1.printWarning)(auto.message);
        }
        catch { }
    }
    try {
        const { firstRunGreeting } = require('../../setup/first-run');
        firstRunGreeting();
    }
    catch { }
    const http = require('http');
    const probeReq = http.request({
        hostname: '127.0.0.1', port: 9876, path: '/health', method: 'GET', timeout: 1000,
    }, (res) => {
        if (res.statusCode === 200) {
            let data = '';
            res.on('data', (chunk) => { data += chunk ? chunk.toString() : ''; });
            res.on('end', () => {
                let up = 0;
                try {
                    up = JSON.parse(data).uptimeSeconds || 0;
                }
                catch { }
                const upH = Math.floor(up / 3600);
                const upM = Math.floor((up % 3600) / 60);
                const upStr = upH > 0 ? `${upH}h ${upM}m` : upM > 0 ? `${upM}m` : `${up}s`;
                (0, utils_1.printSuccess)(`Daemon: already running on port 9876 (uptime ${upStr})`);
                printProjectStatusAndExit();
            });
        }
        else {
            startDaemon();
        }
    });
    probeReq.on('error', () => { startDaemon(); });
    probeReq.on('timeout', () => { probeReq.destroy(); startDaemon(); });
    probeReq.end();
}
function startDaemon() {
    try {
        const { stopDaemon } = require('../../daemon/lifecycle');
        stopDaemon();
        const { execSync } = require('child_process');
        execSync('timeout /t 1 /nobreak >nul 2>&1', { stdio: 'ignore' });
    }
    catch { }
    try {
        const pidFile = path.join(os.homedir(), '.fivo', 'cell', 'daemon.pid');
        try {
            fs.unlinkSync(pidFile);
        }
        catch { }
    }
    catch { }
    (0, utils_1.printDim)('Starting daemon + MCP...');
    try {
        const { spawn } = require('child_process');
        const serverPath = path.join(__dirname, '..', '..', 'daemon', 'server.js');
        const logFile = path.join(os.homedir(), '.fivo', 'cell', 'daemon.log');
        (0, utils_1.ensureDir)(path.dirname(logFile));
        const out = fs.openSync(logFile, 'a');
        const err = fs.openSync(logFile, 'a');
        const child = spawn('node', [serverPath], { detached: true, stdio: ['ignore', out, err] });
        child.unref();
        const pidFile = path.join(os.homedir(), '.fivo', 'cell', 'daemon.pid');
        (0, utils_1.ensureDir)(path.dirname(pidFile));
        fs.writeFileSync(pidFile, String(child.pid), 'utf-8');
        (0, utils_1.printSuccess)(`Daemon + MCP started (PID: ${child.pid})`);
        (0, utils_1.printDim)('Daemon + MCP: http://localhost:9876');
        (0, utils_1.printDim)('MCP endpoint: POST http://localhost:9876/mcp');
        console.log();
        setTimeout(() => { printProjectStatusAndExit(); }, 500);
    }
    catch (e) {
        (0, utils_1.printWarning)('Start failed: ' + String(e));
        process.exit(1);
    }
}
function printProjectStatusAndExit() {
    try {
        const { detectProject, checkScanState, checkWatchState, checkMcpState } = require('../../setup/setup');
        const proj = detectProject(process.cwd());
        const scan = checkScanState(process.cwd());
        const watch = checkWatchState(proj.name);
        const mcp = checkMcpState(os.homedir());
        console.log();
        console.log(utils_1.C.bold('  Project:'), utils_1.C.num(proj.name), utils_1.C.dim(`(${proj.source})`));
        console.log();
        console.log(`    ${scan.done ? utils_1.C.success('OK') : utils_1.C.dim('--')}  scan:   ${scan.reason}`);
        console.log(`    ${watch.done ? utils_1.C.success('OK') : utils_1.C.dim('--')}  watch:  ${watch.reason}`);
        console.log(`    ${mcp.done === mcp.total ? utils_1.C.success('OK') : utils_1.C.dim('--')}  mcp:    ${mcp.done}/${mcp.total} IDEs wired${mcp.needsWrite.length > 0 ? utils_1.C.warn(' (need: ' + mcp.needsWrite.join(', ') + ')') : ''}`);
        console.log();
        const allReady = scan.done && watch.done && mcp.done === mcp.total;
        if (allReady) {
            (0, utils_1.printDim)('✓ Cell is fully ready. Use @cell in your AI chat.');
        }
        else {
            if (!scan.done)
                (0, utils_1.printDim)('  → Run: cell scan');
            if (!watch.done)
                (0, utils_1.printDim)('  → Watcher will auto-start shortly');
            if (mcp.done < mcp.total)
                (0, utils_1.printDim)('  → Run: cell mcp-config');
        }
        console.log();
        process.exit(0);
    }
    catch {
        (0, utils_1.printDim)('Next: cell scan  (scan codebase + build layers)');
        (0, utils_1.printDim)('Then: cell status');
        console.log();
        process.exit(0);
    }
}
function doStop() {
    (0, utils_1.printDim)('Stopping Cell daemon...');
    try {
        const { stopDaemon } = require('../../daemon/lifecycle');
        const result = stopDaemon();
        console.log(result.success ? utils_1.C.success(`  ${result.message}`) : utils_1.C.warn(`  ${result.message}`));
    }
    catch (e) {
        (0, utils_1.printWarning)('Stop failed: ' + String(e));
    }
    try {
        const { unregisterAutostart } = require('../../setup/autostart');
        const auto = unregisterAutostart();
        if (auto.ok && !auto.skipped)
            (0, utils_1.printSuccess)(auto.message);
        else if (!auto.ok)
            (0, utils_1.printWarning)(auto.message);
    }
    catch { }
    console.log();
}
async function doRun(args) {
    console.clear();
    console.log(utils_1.C.primary('  ╔══════════════════════════════╗'));
    console.log(utils_1.C.primary('  ║      FIVO Cell — Quick Start      ║'));
    console.log(utils_1.C.primary('  ╚══════════════════════════════╝'));
    console.log();
    // Step 1: Setup
    console.log(utils_1.C.bold('  [1/3] Setting up...'));
    await doSetup(args);
    // Step 2: Scan
    console.log(utils_1.C.bold('  [2/3] Scanning codebase...'));
    try {
        const { doScan } = require('./scan');
        doScan(['--quick']);
    }
    catch (e) {
        console.log(utils_1.C.dim('  Scan skipped — already scanned'));
    }
    // Step 3: Start daemon
    console.log(utils_1.C.bold('  [3/3] Starting daemon...'));
    doStart([]);
}
async function doSetup(args) {
    const banner = figlet_1.default.textSync('FivoCell', { font: 'ANSI Shadow', horizontalLayout: 'fitted' });
    console.log((0, gradient_string_1.default)(['#FF6B35', '#FFAB91'])(banner));
    (0, utils_1.printDim)('One-time project setup (scan + watcher + MCP)...\n');
    const { runSetup } = require('../../setup/setup');
    const result = await runSetup(process.cwd(), {
        project: args.includes('--project') ? args[args.indexOf('--project') + 1] : undefined,
        skipScan: args.includes('--skip-scan'),
        skipWatch: args.includes('--skip-watch'),
        skipMcp: args.includes('--skip-mcp'),
        dryRun: args.includes('--dry-run'),
        forceRules: args.includes('--force-rules'),
        noRules: args.includes('--no-rules'),
    });
    console.log();
    if (result.success) {
        (0, utils_1.printSuccess)('Setup complete! Type cell start to begin.');
    }
    else {
        if (result.errors.length > 0) {
            for (const e of result.errors)
                (0, utils_1.printWarning)('  ' + e);
        }
        if (result.warnings.length > 0) {
            for (const w of result.warnings)
                (0, utils_1.printDim)('  ' + w);
        }
        if (result.watch && !result.watch.done) {
            (0, utils_1.printDim)('  Watcher will auto-start on next cell start');
        }
        (0, utils_1.printSuccess)('Setup done — ready to go!');
    }
    console.log();
}
//# sourceMappingURL=setup.js.map