import { homedir, platform } from "node:os";
import { join, dirname } from "node:path";
import { mkdir, writeFile, unlink, readFile, stat } from "node:fs/promises";
import { getLogDir } from "../utils/paths.js";
const PLIST_LABEL = "com.pocketcoder.daemon";
const PLIST_FILENAME = `${PLIST_LABEL}.plist`;
const SYSTEMD_SERVICE_NAME = "pocketcoder-daemon.service";
/**
 * Detect the current platform for autostart purposes.
 */
export function detectPlatform() {
    const os = platform();
    switch (os) {
        case "darwin":
            return "macos";
        case "win32":
            return "windows";
        default:
            return "linux";
    }
}
/**
 * Resolve the path to the pocketcoder CLI executable.
 * Uses process.argv[1] to find the CLI entry point, or falls back to
 * a well-known path.
 */
export function resolveDaemonExecPath() {
    // Try to resolve from the current process
    if (process.argv[1]) {
        return process.argv[1];
    }
    return "/usr/local/bin/pocketcoder";
}
/**
 * Get the path where the launchd plist should be written (macOS).
 */
export function getLaunchdPlistPath() {
    return join(homedir(), "Library", "LaunchAgents", PLIST_FILENAME);
}
/**
 * Get the path where the systemd service file should be written (Linux).
 */
export function getSystemdServicePath() {
    return join(homedir(), ".config", "systemd", "user", SYSTEMD_SERVICE_NAME);
}
/**
 * Generate a macOS launchd plist for the daemon.
 */
export function generateLaunchdPlist(execPath) {
    const logDir = getLogDir();
    return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>${PLIST_LABEL}</string>
    <key>ProgramArguments</key>
    <array>
        <string>${execPath}</string>
        <string>start</string>
        <string>--foreground</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>StandardOutPath</key>
    <string>${join(logDir, "daemon.log")}</string>
    <key>StandardErrorPath</key>
    <string>${join(logDir, "daemon.err")}</string>
</dict>
</plist>
`;
}
/**
 * Generate a Linux systemd user service unit for the daemon.
 */
export function generateSystemdService(execPath) {
    return `[Unit]
Description=PocketCoder Daemon
After=network.target

[Service]
Type=simple
ExecStart=${execPath} start --foreground
Restart=on-failure
RestartSec=5
StandardOutput=append:%h/.pocketcoder/logs/daemon.log
StandardError=append:%h/.pocketcoder/logs/daemon.err

[Install]
WantedBy=default.target
`;
}
/**
 * Enable autostart for the current platform.
 * Returns a description of what was configured.
 */
export async function enableAutostart() {
    const plat = detectPlatform();
    const execPath = resolveDaemonExecPath();
    switch (plat) {
        case "macos": {
            const plistPath = getLaunchdPlistPath();
            const plistDir = dirname(plistPath);
            await mkdir(plistDir, { recursive: true });
            const content = generateLaunchdPlist(execPath);
            await writeFile(plistPath, content, { encoding: "utf-8" });
            return `Created launchd plist at ${plistPath}`;
        }
        case "linux": {
            const servicePath = getSystemdServicePath();
            const serviceDir = dirname(servicePath);
            await mkdir(serviceDir, { recursive: true });
            const content = generateSystemdService(execPath);
            await writeFile(servicePath, content, { encoding: "utf-8" });
            return `Created systemd service at ${servicePath}\nRun: systemctl --user enable pocketcoder-daemon && systemctl --user start pocketcoder-daemon`;
        }
        case "windows": {
            return "Windows autostart: Please create a scheduled task manually using Task Scheduler.\nSee: pocketcoder --help for details.";
        }
    }
}
/**
 * Disable autostart for the current platform.
 * Returns a description of what was removed.
 */
export async function disableAutostart() {
    const plat = detectPlatform();
    switch (plat) {
        case "macos": {
            const plistPath = getLaunchdPlistPath();
            try {
                await unlink(plistPath);
                return `Removed launchd plist at ${plistPath}`;
            }
            catch (err) {
                if (err.code === "ENOENT") {
                    return "Autostart was not configured (no plist found)";
                }
                throw err;
            }
        }
        case "linux": {
            const servicePath = getSystemdServicePath();
            try {
                await readFile(servicePath); // check if exists
                await unlink(servicePath);
                return `Removed systemd service at ${servicePath}\nRun: systemctl --user disable pocketcoder-daemon`;
            }
            catch (err) {
                if (err.code === "ENOENT") {
                    return "Autostart was not configured (no service file found)";
                }
                throw err;
            }
        }
        case "windows": {
            return "Windows autostart: Please remove the scheduled task manually using Task Scheduler.";
        }
    }
}
/**
 * Check the current autostart status for the current platform.
 * Returns a human-readable description of whether autostart is configured.
 */
export async function autostartStatus() {
    const plat = detectPlatform();
    switch (plat) {
        case "macos": {
            const plistPath = getLaunchdPlistPath();
            try {
                await stat(plistPath);
                return `Autostart is enabled (launchd plist at ${plistPath})`;
            }
            catch {
                return "Autostart is not configured";
            }
        }
        case "linux": {
            const servicePath = getSystemdServicePath();
            try {
                await stat(servicePath);
                return `Autostart is enabled (systemd service at ${servicePath})`;
            }
            catch {
                return "Autostart is not configured";
            }
        }
        case "windows": {
            return "Windows autostart: Check Task Scheduler for a PocketCoder entry.";
        }
    }
}
//# sourceMappingURL=autostart.js.map