/**
 * Stop Agent Run Use Case
 *
 * Sends SIGTERM to a running agent's worker process and marks it as interrupted.
 * Using "interrupted" (not "cancelled") so the run is resumable via `shep feat resume`.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { injectable, inject } from 'tsyringe';
import { AgentRunStatus } from '../../../domain/generated/output.js';
let StopAgentRunUseCase = class StopAgentRunUseCase {
    agentRunRepository;
    phaseTimingRepository;
    phaseTimingContext;
    constructor(agentRunRepository, phaseTimingRepository, phaseTimingContext) {
        this.agentRunRepository = agentRunRepository;
        this.phaseTimingRepository = phaseTimingRepository;
        this.phaseTimingContext = phaseTimingContext;
    }
    async execute(id) {
        const run = await this.agentRunRepository.findById(id);
        if (!run) {
            return { stopped: false, reason: 'Agent run not found' };
        }
        const terminalStatuses = new Set([
            AgentRunStatus.completed,
            AgentRunStatus.failed,
            AgentRunStatus.interrupted,
            AgentRunStatus.cancelled,
        ]);
        if (terminalStatuses.has(run.status)) {
            return { stopped: false, reason: `Agent run already in terminal state: ${run.status}` };
        }
        if (!run.pid) {
            // No PID — just mark as interrupted (resumable)
            const now = new Date();
            await this.agentRunRepository.updateStatus(id, AgentRunStatus.interrupted, {
                error: 'Stopped by user (no PID)',
                completedAt: now,
                updatedAt: now,
            });
            await this.phaseTimingContext.recordLifecycleEvent('run:stopped', id, this.phaseTimingRepository);
            return { stopped: true, reason: 'Marked as interrupted (no PID to signal)' };
        }
        // Check if process is alive
        let alive = false;
        try {
            process.kill(run.pid, 0);
            alive = true;
        }
        catch {
            alive = false;
        }
        if (alive) {
            // Send SIGTERM for graceful shutdown
            try {
                process.kill(run.pid, 'SIGTERM');
            }
            catch {
                // Process may have died between check and signal
            }
        }
        const now = new Date();
        await this.agentRunRepository.updateStatus(id, AgentRunStatus.interrupted, {
            error: 'Stopped by user',
            completedAt: now,
            updatedAt: now,
        });
        // For alive processes, the worker's SIGTERM handler records run:stopped.
        // For dead processes, record it here since the worker can't.
        if (!alive) {
            await this.phaseTimingContext.recordLifecycleEvent('run:stopped', id, this.phaseTimingRepository);
        }
        return {
            stopped: true,
            reason: alive
                ? `Sent SIGTERM to PID ${run.pid}`
                : `Process already dead, marked as interrupted`,
        };
    }
};
StopAgentRunUseCase = __decorate([
    injectable(),
    __param(0, inject('IAgentRunRepository')),
    __param(1, inject('IPhaseTimingRepository')),
    __param(2, inject('IPhaseTimingContext')),
    __metadata("design:paramtypes", [Object, Object, Object])
], StopAgentRunUseCase);
export { StopAgentRunUseCase };
