// @ts-check

import http from "http";
import path from "path";
import childProcess, { ChildProcess } from "child_process";
const { spawn, spawnSync, execSync } = childProcess;

require("dotenv").config({
    path: path.resolve(__dirname, "../.env"),
});

const environment = process.env.NODE_ENVIRONMENT;

const workingDirectory = path.resolve(__dirname, "../");

// process.stdin.addListener("data", (message) => {
//     console.log("MEssage received =>", message);
// });

process.on("message", (message) => {
    console.log("Message received =>", message);
    if (message == "exit") {
        process.exit();
    }
});

const args = environment?.match(/prod/i) ? ["start"] : ["run", "dev"];

let child: ChildProcess = spawn("bun", args, {
    cwd: workingDirectory,
    stdio: "inherit",
    shell: environment?.match(/prod/i) ? undefined : "bash.exe",
});

const PORT = process.env.DSQL_DEPLOY_SERVER_PORT || 1276;

// deepcode ignore NoRateLimitingForExpensiveWebOperation: <Web Server is only accessible locally>, deepcode ignore HttpToHttps: <Server is not exposed to the web>
http.createServer((req, res) => {
    if (req.url == "/" + process.env.DEPLOY_ROUTE) {
        async function redeploy() {
            /** @type {import("child_process").SpawnSyncOptionsWithBufferEncoding} */
            const options: import("child_process").SpawnSyncOptionsWithBufferEncoding =
                {
                    cwd: workingDirectory,
                    stdio: "inherit",
                };

            if (process.platform?.match(/win/i)) {
                options.shell = "bash.exe";
            }

            if (environment?.match(/prod/i)) {
                spawnSync("git", ["checkout", "."], options);
                spawnSync("git", ["pull"], options);
                spawnSync("bun", ["install"], options);
                spawnSync("bun", ["run", "build"], options);

                try {
                    child.kill();
                    const existingProcessId = execSync(
                        `lsof -i :2763 | grep LISTEN | awk '{print $2}'`
                    );
                    console.log(
                        "Existing Process Id GREPED",
                        existingProcessId.toString()
                    );
                    execSync(`kill ${existingProcessId.toString()}`);
                    // spawnSync("kill", [existingProcessId.toString()], options);
                    // spawnSync("kill", [`${child.pid}`], options);
                } catch (/** @type {any} */ error: any) {
                    console.log("Error killing child process", error.message);
                }

                child = spawn("bun", args, {
                    cwd: workingDirectory,
                    stdio: "inherit",
                    shell: environment?.match(/prod/i) ? undefined : "bash.exe",
                });
            } else {
                spawnSync("git", ["status"], options);
                spawnSync("bun", ["list", "next"], options);

                console.log("Not in production, Continuing ...");
            }
        }

        redeploy();

        res.statusCode = 200;
        res.end("Deployed");
    } else {
        res.statusCode = 402;
        res.end("Unauthorized");
    }
}).listen(PORT, () => console.log("Deployment Server Started on Port", PORT));
