"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.stopCommand = void 0;
exports.stop = stop;
const fs = __importStar(require("fs"));
const timers_1 = require("timers");
const debugFailWrapper_1 = require("../util/debugFailWrapper");
const constants_1 = require("../../../constants");
const debugCommands_1 = require("../../debugCommands");
const DebugSession_1 = require("@mablhq-internal/runtime/debug/DebugSession");
exports.stopCommand = (0, debugCommands_1.defineLeaf)({
    command: `stop <${constants_1.CommandArgSessionId}>`,
    describe: 'Kill the debug Chrome process and delete the session directory',
    builder: (yargs) => {
        yargs.positional(constants_1.CommandArgSessionId, {
            type: 'string',
            demandOption: true,
            describe: 'Debug session id (returned by `session start`).',
        });
    },
    handler: (0, debugFailWrapper_1.debugFailWrapper)(stop),
});
async function stop(parsed) {
    const sessionId = parsed[constants_1.CommandArgSessionId];
    const dir = (0, DebugSession_1.sessionDir)(sessionId);
    const session = tryReadSession(sessionId);
    if (session) {
        await killAndWait(session.browserPid);
    }
    if (!fs.existsSync(dir)) {
        process.stdout.write(JSON.stringify({
            stopped: false,
            sessionId,
            hadSessionFile: false,
            note: `No session directory at ${dir} — already stopped or never started.`,
        }) + '\n');
        return;
    }
    (0, DebugSession_1.deleteSession)(sessionId);
    process.stdout.write(JSON.stringify({
        stopped: true,
        sessionId,
        hadSessionFile: session !== undefined,
    }) + '\n');
}
async function killAndWait(pid, timeoutMs = 3_000) {
    if (!isProcessAlive(pid)) {
        return;
    }
    trySignal(pid, 'SIGTERM');
    const start = Date.now();
    while (Date.now() - start < timeoutMs) {
        if (!isProcessAlive(pid)) {
            return;
        }
        await new Promise((resolve) => (0, timers_1.setTimeout)(resolve, 100));
    }
    trySignal(pid, 'SIGKILL');
    await new Promise((resolve) => (0, timers_1.setTimeout)(resolve, 200));
}
function isProcessAlive(pid) {
    try {
        process.kill(pid, 0);
        return true;
    }
    catch (err) {
        return err.code !== 'ESRCH';
    }
}
function trySignal(pid, signal) {
    try {
        process.kill(pid, signal);
    }
    catch (err) {
        const nodeErr = err;
        if (nodeErr.code !== 'ESRCH') {
            process.stderr.write(`Warning: could not send ${signal} to Chrome (PID ${pid}): ${nodeErr.message}\n`);
        }
    }
}
function tryReadSession(sessionId) {
    const filePath = (0, DebugSession_1.sessionFilePath)(sessionId);
    if (!fs.existsSync(filePath)) {
        return undefined;
    }
    try {
        return JSON.parse(fs.readFileSync(filePath, 'utf8'));
    }
    catch {
        return undefined;
    }
}
