import { createExecutionResources, resolveCommandFlags } from "../../shared.js";
import { attachJob, createRuntimeState, resolveJob, syncJob, waitForGracefulStop } from "./shared.js";
export function registerRuntimeJobsStopCommand(jobs, root, container) {
    jobs
        .command("stop")
        .description("Stop a detached runtime job.")
        .argument("[jobId]", "Detached job id")
        .option("--sync", "Download the workspace after stopping")
        .option("--force-sync", "Overwrite local files when syncing")
        .action(async (jobId, options) => {
        await executeRuntimeJobsStop(root, container, jobId, options);
    });
}
async function executeRuntimeJobsStop(root, container, jobId, options) {
    const flags = resolveCommandFlags(root);
    const resources = createExecutionResources(container, flags, "runtime:jobs:stop");
    const state = createRuntimeState(container);
    const entry = await resolveJob(state, jobId, "running");
    const shouldSync = options.sync === true;
    if (flags.dryRun) {
        const syncSuffix = shouldSync ? " and sync its workspace" : "";
        resources.logger.dryRun(`Dry run: would stop runtime job ${entry.id}${syncSuffix}.`);
        return;
    }
    const { handle } = await attachJob(entry);
    await waitForGracefulStop(handle);
    await state.jobs.update(entry.id, {
        status: "killed",
        exit_code: 130,
        exited_at: new Date().toISOString()
    });
    if (shouldSync) {
        await syncJob(entry, { forceSync: options.forceSync === true, close: false });
    }
    resources.logger.success(`Stopped runtime job ${entry.id}.`);
}
//# sourceMappingURL=stop.js.map