import { spawn, ChildProcess } from "child_process";
import { resolveEnv } from "./env-resolver.js";
export function startService(service, databases, secrets, port, onLog) {
    // Determine command: prefer dev.command, fallback to command
    const command = service.dev?.command ?? service.command;
    if (!command) {
        throw new Error(`Service "${service.name}" has no command`);
    }
    // Resolve environment variables
    const resolvedEnv = resolveEnv(service.env, databases, secrets, port);
    // Spawn the process
    const child = spawn(command, {
        shell: true,
        cwd: process.cwd(),
        env: {
            ...process.env,
            ...resolvedEnv,
        },
        stdio: ["ignore", "pipe", "pipe"],
    });
    // Handle stdout
    child.stdout?.on("data", (data) => {
        const lines = data.toString().split("\n");
        for (const line of lines) {
            if (line.trim()) {
                onLog({ service: service.name, text: line, stream: "stdout" });
            }
        }
    });
    // Handle stderr
    child.stderr?.on("data", (data) => {
        const lines = data.toString().split("\n");
        for (const line of lines) {
            if (line.trim()) {
                onLog({ service: service.name, text: line, stream: "stderr" });
            }
        }
    });
    return {
        name: service.name,
        port,
        process: child,
        async stop() {
            return new Promise((resolve) => {
                if (child.killed) {
                    resolve();
                    return;
                }
                child.once("exit", () => resolve());
                child.kill("SIGTERM");
                // Force kill after 5 seconds
                setTimeout(() => {
                    if (!child.killed) {
                        child.kill("SIGKILL");
                    }
                }, 5000);
            });
        },
    };
}
//# sourceMappingURL=service-runner.js.map