import express from "express";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { getManagerStatus, readDaemonLogs, restartDaemon, startDaemon, stopDaemon, } from "./daemon-service.js";
const DEFAULT_LISTEN = "127.0.0.1:6770";
function parseListenTarget(value) {
    const lastColon = value.lastIndexOf(":");
    if (lastColon <= 0) {
        throw new Error(`Invalid PASEO_MANAGER_LISTEN: ${value}`);
    }
    const host = value.slice(0, lastColon);
    const port = Number.parseInt(value.slice(lastColon + 1), 10);
    if (!Number.isFinite(port) || port <= 0) {
        throw new Error(`Invalid port in PASEO_MANAGER_LISTEN: ${value}`);
    }
    return { host, port };
}
function resolvePublicDir() {
    const moduleDir = path.dirname(fileURLToPath(import.meta.url));
    const bundledPublic = path.join(moduleDir, "public");
    if (existsSync(bundledPublic)) {
        return bundledPublic;
    }
    return path.join(moduleDir, "..", "public");
}
const publicDir = resolvePublicDir();
const app = express();
app.use(express.json());
app.get("/api/status", async (_req, res) => {
    try {
        const status = await getManagerStatus();
        res.json(status);
    }
    catch (error) {
        res.status(500).json({
            error: error instanceof Error ? error.message : String(error),
        });
    }
});
app.get("/api/logs", (req, res) => {
    const tail = Number.parseInt(String(req.query.tail ?? "250"), 10);
    const safeTail = Number.isFinite(tail) ? Math.min(Math.max(tail, 50), 2000) : 250;
    res.json(readDaemonLogs(safeTail));
});
app.post("/api/daemon/start", async (_req, res) => {
    try {
        const result = await startDaemon();
        res.json(result);
    }
    catch (error) {
        res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
    }
});
app.post("/api/daemon/stop", async (_req, res) => {
    try {
        const result = await stopDaemon();
        res.json(result);
    }
    catch (error) {
        res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
    }
});
app.post("/api/daemon/restart", async (_req, res) => {
    try {
        const result = await restartDaemon();
        res.json(result);
    }
    catch (error) {
        res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
    }
});
app.use(express.static(publicDir));
export function startManagerServer(listenTarget) {
    const { host, port } = parseListenTarget(listenTarget);
    return new Promise((resolve) => {
        app.listen(port, host, () => {
            console.log(`Kong Link Server Manager: http://${host}:${port}`);
            resolve();
        });
    });
}
const listenTarget = process.env.PASEO_MANAGER_LISTEN?.trim() || DEFAULT_LISTEN;
function isDirectExecution() {
    const entry = process.argv[1];
    if (!entry) {
        return false;
    }
    return import.meta.url === pathToFileURL(entry).href;
}
if (isDirectExecution()) {
    void startManagerServer(listenTarget);
}
