"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.register = register;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const ui_1 = require("../ui");
const dashboard_1 = require("../installer/dashboard");
const SERVER_STATE_FILE = 'typesense-server.json';
function readState(kirographDir) {
    try {
        return JSON.parse(fs.readFileSync(path.join(kirographDir, SERVER_STATE_FILE), 'utf8'));
    }
    catch {
        return null;
    }
}
function isAlive(pid) {
    try {
        process.kill(pid, 0);
        return true;
    }
    catch {
        return false;
    }
}
function register(program) {
    const ts = program
        .command('typesense [projectPath]')
        .description('Manage the Typesense engine and dashboard');
    // ── start ──────────────────────────────────────────────────────────────────
    ts.command('start [projectPath]')
        .description('Start the Typesense server (if not running) and open the local dashboard')
        .action(async (projectPath) => {
        const target = path.resolve(projectPath ?? process.cwd());
        const kirographDir = path.join(target, '.kirograph');
        // Check if already running
        const saved = readState(kirographDir);
        if (saved && isAlive(saved.pid)) {
            console.log(`\n  ${ui_1.green}✓${ui_1.reset} Typesense already running  ${ui_1.dim}(pid ${saved.pid}, port ${saved.apiPort})${ui_1.reset}`);
        }
        else {
            // Start via TypesenseIndex.initialize() — it handles binary download,
            // spawn, health check, and writes the state file.
            console.log();
            const { TypesenseIndex } = await Promise.resolve().then(() => __importStar(require('../../vectors/typesense-index')));
            const index = new TypesenseIndex(kirographDir);
            await index.initialize();
            if (!index.isAvailable()) {
                console.log(`  Typesense failed to start.\n`);
                return;
            }
            index.close(); // detach client; server keeps running as daemon
        }
        // Open dashboard (reads fresh state file for the actual port)
        await (0, dashboard_1.openTypesenseDashboard)(target);
        console.log(`  ${ui_1.dim}Press Ctrl+C to close the dashboard (Typesense keeps running — use ${ui_1.reset}kg typesense stop${ui_1.dim} to shut it down).${ui_1.reset}\n`);
        process.on('SIGINT', () => process.exit(0));
    });
    // ── stop ───────────────────────────────────────────────────────────────────
    ts.command('stop [projectPath]')
        .description('Stop the Typesense server')
        .action((projectPath) => {
        const target = path.resolve(projectPath ?? process.cwd());
        const kirographDir = path.join(target, '.kirograph');
        const stateFile = path.join(kirographDir, SERVER_STATE_FILE);
        console.log();
        const saved = readState(kirographDir);
        if (!saved) {
            console.log(`  ${ui_1.dim}No running Typesense server found.${ui_1.reset}\n`);
            return;
        }
        let killed = false;
        if (isAlive(saved.pid)) {
            try {
                process.kill(saved.pid, 'SIGTERM');
                killed = true;
            }
            catch { /* ignore */ }
        }
        try {
            fs.unlinkSync(stateFile);
        }
        catch { /* ignore */ }
        if (killed) {
            console.log(`  ${ui_1.green}✓${ui_1.reset} ${(0, ui_1.label)('Stopped')} Typesense server  ${ui_1.dim}(pid ${saved.pid}, port ${saved.apiPort})${ui_1.reset}`);
        }
        else {
            console.log(`  ${ui_1.dim}Typesense server (pid ${saved.pid}) was not running — state file cleaned up.${ui_1.reset}`);
        }
        console.log();
    });
}
//# sourceMappingURL=typesense.js.map