"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.startDaemon = startDaemon;
exports.stopDaemon = stopDaemon;
exports.restartDaemon = restartDaemon;
exports.ensureDaemon = ensureDaemon;
exports.statusDaemon = statusDaemon;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
const http = __importStar(require("http"));
const PID_FILE = path.join(os.homedir(), '.fivo', 'cell', 'daemon.pid');
const PORT = 9876;
function ensureDir() {
    const dir = path.dirname(PID_FILE);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}
function writePid(pid) {
    ensureDir();
    fs.writeFileSync(PID_FILE, String(pid), 'utf-8');
}
function readPid() {
    try {
        return parseInt(fs.readFileSync(PID_FILE, 'utf-8').trim(), 10);
    }
    catch {
        return null;
    }
}
function removePid() {
    try {
        fs.unlinkSync(PID_FILE);
    }
    catch { }
}
function isProcessRunning(pid) {
    try {
        process.kill(pid, 0);
        return true;
    }
    catch {
        return false;
    }
}
function healthCheck() {
    return new Promise((resolve) => {
        const req = http.get(`http://localhost:${PORT}/health`, (res) => {
            resolve(res.statusCode === 200);
        });
        req.on('error', () => resolve(false));
        req.setTimeout(3000, () => { req.destroy(); resolve(false); });
    });
}
// ─── Self-healing daemon ─────────────────────────────────────────────────────
let daemonProcess = null;
let restartCount = 0;
const MAX_RESTARTS = 10;
function startDaemonProcess() {
    const ext = path.extname(__filename) === '.ts' ? '.ts' : '.js';
    const serverPath = path.join(__dirname, '..', 'daemon', `server${ext}`);
    const args = ext === '.ts' ? ['--loader', 'ts-node/esm', serverPath] : [serverPath];
    const child = (0, child_process_1.spawn)('node', args, {
        detached: true,
        stdio: 'ignore',
    });
    child.unref();
    if (child.pid)
        writePid(child.pid);
    child.on('exit', (code) => {
        console.log(`[cell] Daemon exited (code ${code})`);
        daemonProcess = null;
        // Auto-restart if not intentionally stopped
        if (restartCount < MAX_RESTARTS) {
            restartCount++;
            console.log(`[cell] Auto-restarting daemon (attempt ${restartCount})...`);
            setTimeout(() => {
                startDaemonProcess();
            }, 2000);
        }
    });
    child.on('error', (err) => {
        console.error(`[cell] Daemon error: ${err.message}`);
        daemonProcess = null;
    });
    return child;
}
async function startDaemon() {
    // Check if already running
    const existingPid = readPid();
    if (existingPid && isProcessRunning(existingPid)) {
        const healthy = await healthCheck();
        if (healthy) {
            startWatcherIfNeeded();
            return { pid: existingPid, port: PORT };
        }
        // Stale — kill and restart
        try {
            process.kill(existingPid, 'SIGKILL');
        }
        catch { }
        removePid();
        await new Promise((r) => setTimeout(r, 500));
    }
    removePid();
    restartCount = 0;
    return new Promise((resolve, reject) => {
        daemonProcess = startDaemonProcess();
        // Wait for health check
        let attempts = 0;
        const maxAttempts = 15;
        const check = setInterval(async () => {
            attempts++;
            const healthy = await healthCheck();
            if (healthy && daemonProcess?.pid) {
                clearInterval(check);
                startWatcherIfNeeded();
                resolve({ pid: daemonProcess.pid, port: PORT });
            }
            else if (attempts >= maxAttempts) {
                clearInterval(check);
                reject(new Error('Daemon failed to start after 15 attempts'));
            }
        }, 1000);
    });
}
async function startWatcherIfNeeded() {
    try {
        // Auto-start file watcher for the current project
        const { LiveWatcher } = require('../watcher/live-watcher');
        const watcher = new LiveWatcher(process.cwd());
        watcher.start();
    }
    catch { /* watcher may not be needed */ }
}
function stopDaemon() {
    const pid = readPid();
    if (!pid)
        return { success: true, message: 'Already stopped.' };
    if (!isProcessRunning(pid)) {
        removePid();
        return { success: true, message: 'Was not running. Cleaned up.' };
    }
    try {
        process.kill(pid, 'SIGTERM');
        removePid();
        daemonProcess = null;
        return { success: true, message: `Stopped (PID: ${pid})` };
    }
    catch {
        removePid();
        return { success: true, message: 'Terminated.' };
    }
}
async function restartDaemon() {
    stopDaemon();
    await new Promise((r) => setTimeout(r, 1000));
    return startDaemon();
}
async function ensureDaemon(opts = {}) {
    const pid = readPid();
    if (pid && isProcessRunning(pid)) {
        const healthy = await healthCheck();
        if (healthy)
            return true;
    }
    if (!opts.silent)
        console.log('[cell] Starting daemon...');
    try {
        await startDaemon();
        if (!opts.silent)
            console.log('[cell] Daemon ready.');
        return true;
    }
    catch (err) {
        if (!opts.silent) {
            const msg = err instanceof Error ? err.message : String(err);
            console.error(`[cell] Failed: ${msg}`);
        }
        return false;
    }
}
async function statusDaemon() {
    const pid = readPid();
    const alive = pid ? isProcessRunning(pid) : false;
    if (!alive)
        return { running: false, pid: null, port: PORT, health: null };
    const healthy = await healthCheck();
    if (!healthy)
        return { running: false, pid, port: PORT, health: null };
    try {
        const healthData = await new Promise((resolve, reject) => {
            http.get(`http://localhost:${PORT}/health`, (res) => {
                let data = '';
                res.on('data', (chunk) => (data += chunk));
                res.on('end', () => { try {
                    resolve(JSON.parse(data));
                }
                catch {
                    reject(new Error('parse error'));
                } });
            }).on('error', reject);
        });
        return { running: true, pid, port: PORT, health: healthData };
    }
    catch {
        return { running: false, pid, port: PORT, health: null };
    }
}
//# sourceMappingURL=lifecycle.js.map