"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 http = __importStar(require("http"));
const ui_1 = require("../ui");
const qdrant_dashboard_1 = require("../installer/qdrant-dashboard");
const SERVER_STATE_FILE = 'qdrant-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;
    }
}
/** Check if the Qdrant dashboard endpoint returns something other than 404. */
function dashboardReachable(port) {
    return new Promise(resolve => {
        const req = http.get(`http://127.0.0.1:${port}/dashboard`, res => {
            resolve(res.statusCode !== 404);
            res.resume();
        });
        req.on('error', () => resolve(false));
        req.setTimeout(1000, () => { req.destroy(); resolve(false); });
    });
}
function register(program) {
    const cmd = program
        .command('qdrant [projectPath]')
        .description('Manage the Qdrant engine and dashboard');
    // ── start ──────────────────────────────────────────────────────────────────
    cmd.command('start [projectPath]')
        .description('Start the Qdrant server (if not running) and open the dashboard')
        .action(async (projectPath) => {
        const target = path.resolve(projectPath ?? process.cwd());
        const kirographDir = path.join(target, '.kirograph');
        // 1. Ensure UI files are downloaded BEFORE starting Qdrant so
        //    QdrantIndex.initialize() finds them and sets STATIC_CONTENT_DIR.
        const uiReady = await (0, qdrant_dashboard_1.ensureQdrantUI)(target);
        if (!uiReady) {
            console.log(`  Could not download Qdrant Web UI.\n`);
            return;
        }
        // 2. If already running, check whether the dashboard is actually served.
        //    If not (started without static dir), restart so it picks up the files.
        const saved = readState(kirographDir);
        if (saved && isAlive(saved.pid)) {
            const hasDashboard = await dashboardReachable(saved.port);
            if (!hasDashboard) {
                // Restart with static content dir now that UI files are present
                try {
                    process.kill(saved.pid, 'SIGTERM');
                }
                catch { /* ignore */ }
                await new Promise(r => setTimeout(r, 400));
                try {
                    fs.unlinkSync(path.join(kirographDir, SERVER_STATE_FILE));
                }
                catch { /* ignore */ }
            }
            else {
                console.log(`\n  ${ui_1.green}✓${ui_1.reset} Qdrant already running with dashboard  ${ui_1.dim}(pid ${saved.pid}, port ${saved.port})${ui_1.reset}`);
                await (0, qdrant_dashboard_1.openQdrantDashboard)(target);
                console.log(`  ${ui_1.dim}Qdrant keeps running in the background — use ${ui_1.reset}kg qdrant stop${ui_1.dim} to shut it down.${ui_1.reset}\n`);
                return;
            }
        }
        // 3. Spawn (or re-spawn) Qdrant — files are in place so STATIC_CONTENT_DIR is set
        console.log();
        const { QdrantIndex } = await Promise.resolve().then(() => __importStar(require('../../vectors/qdrant-index')));
        const index = new QdrantIndex(kirographDir);
        await index.initialize();
        if (!index.isAvailable()) {
            console.log(`  Qdrant failed to start.\n`);
            return;
        }
        index.close();
        await (0, qdrant_dashboard_1.openQdrantDashboard)(target);
        console.log(`  ${ui_1.dim}Qdrant keeps running in the background — use ${ui_1.reset}kg qdrant stop${ui_1.dim} to shut it down.${ui_1.reset}\n`);
    });
    // ── stop ───────────────────────────────────────────────────────────────────
    cmd.command('stop [projectPath]')
        .description('Stop the Qdrant 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 Qdrant 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')} Qdrant server  ${ui_1.dim}(pid ${saved.pid}, port ${saved.port})${ui_1.reset}`);
        }
        else {
            console.log(`  ${ui_1.dim}Qdrant server (pid ${saved.pid}) was not running — state file cleaned up.${ui_1.reset}`);
        }
        console.log();
    });
}
//# sourceMappingURL=qdrant.js.map