"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.loadWorkerRegistry = loadWorkerRegistry;
exports.saveWorkerRegistry = saveWorkerRegistry;
exports.registerWorkerPath = registerWorkerPath;
exports.unregisterWorkerPath = unregisterWorkerPath;
exports.listWorkerPaths = listWorkerPaths;
exports.clearWorkerRegistry = clearWorkerRegistry;
exports.startAllWorkers = startAllWorkers;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
function getWorkerRegistryPath() {
    return path.join(os.homedir(), ".knowhow", "workers.json");
}
async function loadWorkerRegistry() {
    const registryPath = getWorkerRegistryPath();
    try {
        if (fs.existsSync(registryPath)) {
            const content = await fs.promises.readFile(registryPath, "utf8");
            return JSON.parse(content);
        }
    }
    catch (error) {
        console.warn("Failed to load worker registry:", error);
    }
    return { workers: [] };
}
async function saveWorkerRegistry(registry) {
    const registryPath = getWorkerRegistryPath();
    const dir = path.dirname(registryPath);
    if (!fs.existsSync(dir)) {
        await fs.promises.mkdir(dir, { recursive: true });
    }
    await fs.promises.writeFile(registryPath, JSON.stringify(registry, null, 2), "utf8");
}
async function registerWorkerPath(workerPath) {
    const registry = await loadWorkerRegistry();
    const normalizedPath = path.resolve(workerPath);
    if (!registry.workers.includes(normalizedPath)) {
        registry.workers.push(normalizedPath);
        await saveWorkerRegistry(registry);
        console.log(`✓ Registered worker path: ${normalizedPath}`);
    }
    else {
        console.log(`Worker path already registered: ${normalizedPath}`);
    }
}
async function unregisterWorkerPath(workerPath) {
    const registry = await loadWorkerRegistry();
    const normalizedPath = path.resolve(workerPath);
    const index = registry.workers.indexOf(normalizedPath);
    if (index !== -1) {
        registry.workers.splice(index, 1);
        await saveWorkerRegistry(registry);
        console.log(`✓ Unregistered worker path: ${normalizedPath}`);
    }
    else {
        console.log(`Worker path not found in registry: ${normalizedPath}`);
    }
}
async function listWorkerPaths() {
    const registry = await loadWorkerRegistry();
    return registry.workers;
}
async function clearWorkerRegistry() {
    await saveWorkerRegistry({ workers: [] });
    console.log("✓ Cleared all registered worker paths");
}
async function startAllWorkers() {
    const workerPaths = await listWorkerPaths();
    if (workerPaths.length === 0) {
        console.log("No workers registered. Use 'knowhow worker --register' to register workers.");
        return;
    }
    console.log(`Starting ${workerPaths.length} worker(s)...`);
    const processes = [];
    for (const workerPath of workerPaths) {
        if (!fs.existsSync(workerPath)) {
            console.warn(`⚠ Worker path does not exist: ${workerPath}`);
            continue;
        }
        console.log(`Starting worker at: ${workerPath}`);
        const workerProcess = (0, child_process_1.spawn)("knowhow", ["worker"], {
            cwd: workerPath,
            stdio: "inherit",
            detached: false,
        });
        workerProcess.on("error", (error) => {
            console.error(`Error in worker at ${workerPath}:`, error);
        });
        workerProcess.on("exit", (code, signal) => {
            console.log(`Worker at ${workerPath} exited with code ${code} and signal ${signal}`);
        });
        processes.push({ path: workerPath, process: workerProcess });
    }
    console.log(`\n✓ Started ${processes.length} worker(s)`);
    console.log("Press Ctrl+C to stop all workers\n");
    const shutdownHandler = () => {
        console.log("\nShutting down all workers...");
        for (const { path: workerPath, process: proc } of processes) {
            console.log(`Stopping worker at: ${workerPath}`);
            proc.kill("SIGTERM");
        }
        setTimeout(() => {
            for (const { process: proc } of processes) {
                if (!proc.killed) {
                    proc.kill("SIGKILL");
                }
            }
            process.exit(0);
        }, 5000);
    };
    process.on("SIGINT", shutdownHandler);
    process.on("SIGTERM", shutdownHandler);
    await new Promise(() => { });
}
//# sourceMappingURL=workerRegistry.js.map