import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { configureStartupConfig } from "./startup-config-wizard.js";
const SYSTEMD_SERVICE_NAME = "awsb.service";
const DEFAULT_SYSTEMD_UNIT_PATH = `/etc/systemd/system/${SYSTEMD_SERVICE_NAME}`;
function getDefaultPackageRoot() {
    const currentFile = fileURLToPath(import.meta.url);
    return path.resolve(path.dirname(currentFile), "..", "..");
}
export function readPackageVersion(packageRoot = getDefaultPackageRoot()) {
    const packageJsonPath = path.join(packageRoot, "package.json");
    const metadata = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
    return metadata.version || "unknown";
}
function defaultRunCommand(command, args) {
    const result = spawnSync(command, args, {
        shell: process.platform === "win32",
        stdio: "inherit",
    });
    return { status: result.status, error: result.error };
}
function defaultStdout(message) {
    process.stdout.write(`${message}\n`);
}
function defaultStderr(message) {
    process.stderr.write(`${message}\n`);
}
function isVersionCommand(command) {
    return command === "-v" || command === "--version" || command === "version";
}
function quoteSystemdExecArg(value) {
    return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
function getDefaultExecutablePath() {
    return process.argv[1]
        ? path.resolve(process.argv[1])
        : fileURLToPath(import.meta.url);
}
/**
 * 生成 systemd unit 内容，主流程是用当前 Node 可执行文件启动当前 CLI 入口。
 */
export function createSystemdUnitContent(executablePath) {
    const execStart = [process.execPath, executablePath]
        .map((part) => quoteSystemdExecArg(part))
        .join(" ");
    return [
        "[Unit]",
        "Description=AgentsWorkStudio Runtime Bridge",
        "After=network-online.target",
        "Wants=network-online.target",
        "",
        "[Service]",
        "Type=simple",
        "Environment=AWS_BRIDGE_SKIP_SETUP=true",
        `ExecStart=${execStart}`,
        "Restart=on-failure",
        "RestartSec=5s",
        "",
        "[Install]",
        "WantedBy=multi-user.target",
        "",
    ].join("\n");
}
function runSystemctl(runCommand, args) {
    return runCommand("systemctl", args);
}
function systemctlFailureMessage(action, result) {
    if (result.error) {
        return `[runtime-bridge] ${action}失败: ${result.error.message}`;
    }
    return `[runtime-bridge] ${action}失败，systemctl 退出码: ${result.status ?? "unknown"}`;
}
function commandSucceeded(result) {
    return !result.error && result.status === 0;
}
function ensureLinuxSystemd(platform, stderr) {
    if (platform === "linux") {
        return true;
    }
    stderr("[runtime-bridge] service 命令仅支持 Linux systemd 环境。");
    return false;
}
function printServiceUsage(stdout) {
    stdout("Usage: awsb service <install|uninstall>");
}
/**
 * 安装 systemd 服务，主干流程是写入 unit、重载 systemd、启用开机自启，并在未运行时启动服务。
 */
function installSystemdService(options) {
    if (!ensureLinuxSystemd(options.platform, options.stderr)) {
        return { handled: true, exitCode: 1 };
    }
    const unitContent = createSystemdUnitContent(options.executablePath);
    try {
        mkdirSync(path.dirname(options.serviceUnitPath), { recursive: true });
        writeFileSync(options.serviceUnitPath, unitContent, {
            encoding: "utf-8",
            mode: 0o644,
        });
    }
    catch (error) {
        const err = error instanceof Error ? error : new Error(String(error));
        options.stderr(`[runtime-bridge] 写入 systemd unit 失败: ${err.message}`);
        return { handled: true, exitCode: 1 };
    }
    const daemonReloadResult = runSystemctl(options.runCommand, ["daemon-reload"]);
    if (!commandSucceeded(daemonReloadResult)) {
        options.stderr(systemctlFailureMessage("重载 systemd", daemonReloadResult));
        return { handled: true, exitCode: daemonReloadResult.status ?? 1 };
    }
    const enableResult = runSystemctl(options.runCommand, [
        "enable",
        SYSTEMD_SERVICE_NAME,
    ]);
    if (!commandSucceeded(enableResult)) {
        options.stderr(systemctlFailureMessage("启用 awsb 开机自启", enableResult));
        return { handled: true, exitCode: enableResult.status ?? 1 };
    }
    const activeResult = runSystemctl(options.runCommand, [
        "is-active",
        "--quiet",
        SYSTEMD_SERVICE_NAME,
    ]);
    if (activeResult.error) {
        options.stderr(systemctlFailureMessage("检查 awsb 服务状态", activeResult));
        return { handled: true, exitCode: 1 };
    }
    if (activeResult.status !== 0) {
        const startResult = runSystemctl(options.runCommand, [
            "start",
            SYSTEMD_SERVICE_NAME,
        ]);
        if (!commandSucceeded(startResult)) {
            options.stderr(systemctlFailureMessage("启动 awsb 服务", startResult));
            return { handled: true, exitCode: startResult.status ?? 1 };
        }
        options.stdout("[runtime-bridge] awsb systemd 服务已安装、已启用开机自启并已启动。");
        return { handled: true, exitCode: 0 };
    }
    options.stdout("[runtime-bridge] awsb systemd 服务已安装并已启用开机自启；服务已在运行。");
    return { handled: true, exitCode: 0 };
}
/**
 * 卸载 systemd 服务，主干流程是按需停止、禁用自启、删除 unit，并重载 systemd。
 */
function uninstallSystemdService(options) {
    if (!ensureLinuxSystemd(options.platform, options.stderr)) {
        return { handled: true, exitCode: 1 };
    }
    const unitExists = existsSync(options.serviceUnitPath);
    const activeResult = runSystemctl(options.runCommand, [
        "is-active",
        "--quiet",
        SYSTEMD_SERVICE_NAME,
    ]);
    if (activeResult.error) {
        options.stderr(systemctlFailureMessage("检查 awsb 服务状态", activeResult));
        return { handled: true, exitCode: 1 };
    }
    if (activeResult.status === 0) {
        const stopResult = runSystemctl(options.runCommand, [
            "stop",
            SYSTEMD_SERVICE_NAME,
        ]);
        if (!commandSucceeded(stopResult)) {
            options.stderr(systemctlFailureMessage("停止 awsb 服务", stopResult));
            return { handled: true, exitCode: stopResult.status ?? 1 };
        }
    }
    const disableResult = runSystemctl(options.runCommand, [
        "disable",
        SYSTEMD_SERVICE_NAME,
    ]);
    if (disableResult.error || (disableResult.status !== 0 && unitExists)) {
        options.stderr(systemctlFailureMessage("禁用 awsb 开机自启", disableResult));
        return { handled: true, exitCode: disableResult.status ?? 1 };
    }
    if (unitExists) {
        try {
            unlinkSync(options.serviceUnitPath);
        }
        catch (error) {
            const err = error instanceof Error ? error : new Error(String(error));
            options.stderr(`[runtime-bridge] 删除 systemd unit 失败: ${err.message}`);
            return { handled: true, exitCode: 1 };
        }
    }
    else {
        options.stdout("[runtime-bridge] awsb systemd unit 不存在，跳过删除。");
    }
    const daemonReloadResult = runSystemctl(options.runCommand, ["daemon-reload"]);
    if (!commandSucceeded(daemonReloadResult)) {
        options.stderr(systemctlFailureMessage("重载 systemd", daemonReloadResult));
        return { handled: true, exitCode: daemonReloadResult.status ?? 1 };
    }
    options.stdout("[runtime-bridge] awsb systemd 服务已卸载。");
    return { handled: true, exitCode: 0 };
}
function handleServiceCommand(argv, options, stdout, stderr) {
    const subcommand = argv[1];
    if (!subcommand ||
        subcommand === "-h" ||
        subcommand === "--help" ||
        subcommand === "help") {
        printServiceUsage(stdout);
        return { handled: true, exitCode: subcommand ? 0 : 1 };
    }
    const serviceOptions = {
        stdout,
        stderr,
        runCommand: options.runCommand || defaultRunCommand,
        platform: options.platform || process.platform,
        serviceUnitPath: options.serviceUnitPath || DEFAULT_SYSTEMD_UNIT_PATH,
        executablePath: options.executablePath || getDefaultExecutablePath(),
    };
    if (subcommand === "install") {
        return installSystemdService(serviceOptions);
    }
    if (subcommand === "uninstall") {
        return uninstallSystemdService(serviceOptions);
    }
    stderr(`[runtime-bridge] 未知 service 子命令: ${subcommand}`);
    printServiceUsage(stdout);
    return { handled: true, exitCode: 1 };
}
export async function handleCliCommand(options = {}) {
    const argv = options.argv || process.argv.slice(2);
    const command = argv[0];
    const stdout = options.stdout || defaultStdout;
    const stderr = options.stderr || defaultStderr;
    if (isVersionCommand(command)) {
        stdout(`aws-runtime-bridge ${readPackageVersion(options.packageRoot)}`);
        return { handled: true, exitCode: 0 };
    }
    if (command === "update") {
        stdout("[runtime-bridge] 正在更新 aws-runtime-bridge 到最新版本...");
        const runCommand = options.runCommand || defaultRunCommand;
        const result = runCommand("npm", [
            "install",
            "-g",
            "aws-runtime-bridge@latest",
        ]);
        if (result.error) {
            stderr(`[runtime-bridge] 更新失败: ${result.error.message}`);
            return { handled: true, exitCode: 1 };
        }
        if (result.status !== 0) {
            stderr(`[runtime-bridge] 更新失败，npm 退出码: ${result.status ?? "unknown"}`);
            return { handled: true, exitCode: result.status ?? 1 };
        }
        stdout("[runtime-bridge] 更新完成。请重新运行 awsb -v 查看当前版本。");
        return { handled: true, exitCode: 0 };
    }
    if (command === "config") {
        const configure = options.configure || configureStartupConfig;
        const result = await configure();
        return { handled: true, exitCode: result === "configured" ? 0 : 1 };
    }
    if (command === "service") {
        return handleServiceCommand(argv, options, stdout, stderr);
    }
    return { handled: false, exitCode: 0 };
}
