/**
 * Resume Application Workflow Use Case
 *
 * Resumes an interrupted application-creation workflow by:
 * 1. Resetting any `interrupted` steps back to `pending`
 * 2. Walking remaining steps: for each pending step, send its prompt
 *    to the agent, wait for the turn to complete, mark it done.
 *
 * The agent SDK session is resumed (same conversation context) because
 * the session service looks up the previous `agentSessionId` from the DB.
 */
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 { WorkflowStepStatus } from '../../../domain/generated/output.js';
import { featureIdForApplication } from '../../../domain/shared/feature-id.js';
import { APPLICATION_CREATION_WORKFLOW } from './application-creation.workflow.js';
let ResumeApplicationWorkflowUseCase = class ResumeApplicationWorkflowUseCase {
    appRepo;
    stepRepo;
    session;
    sendMessage;
    sessionRepo;
    constructor(appRepo, stepRepo, session, sendMessage, sessionRepo) {
        this.appRepo = appRepo;
        this.stepRepo = stepRepo;
        this.session = session;
        this.sendMessage = sendMessage;
        this.sessionRepo = sessionRepo;
    }
    async execute(input) {
        const app = await this.appRepo.findById(input.applicationId);
        if (!app)
            throw new Error(`Application ${input.applicationId} not found`);
        const featureId = featureIdForApplication(app.id);
        const steps = await this.stepRepo.listByFeature(featureId);
        if (steps.length === 0)
            return;
        // Reset interrupted steps back to pending
        for (const step of steps) {
            if (step.status === WorkflowStepStatus.interrupted) {
                await this.stepRepo.updateStatus(step.id, WorkflowStepStatus.pending);
                this.session.notifyWorkflowStep(featureId, await this.refreshStep(step.id));
            }
        }
        // Walk steps — skip done ones, execute pending ones sequentially
        for (let i = 0; i < steps.length; i++) {
            const step = steps[i];
            const definition = APPLICATION_CREATION_WORKFLOW.steps[i];
            if (!definition)
                break;
            // Refresh status (might have been reset above)
            const current = await this.stepRepo.findById(step.id);
            if (!current)
                break;
            if (current.status === WorkflowStepStatus.done)
                continue;
            if (current.status !== WorkflowStepStatus.pending)
                break;
            // Mark running
            await this.stepRepo.updateStatus(step.id, WorkflowStepStatus.running);
            this.session.notifyWorkflowStep(featureId, await this.refreshStep(step.id));
            this.session.setActiveStep(featureId, step.id);
            const turnDone = this.session.waitForTurnDone(featureId);
            try {
                await this.sendMessage.execute({
                    featureId,
                    content: definition.prompt,
                    worktreePath: app.repositoryPath,
                    model: app.modelOverride,
                    agentType: app.agentType,
                });
                await turnDone;
                await this.stepRepo.updateStatus(step.id, WorkflowStepStatus.done, {
                    summary: definition.title,
                });
                this.session.notifyWorkflowStep(featureId, await this.refreshStep(step.id));
            }
            catch (err) {
                await this.stepRepo.updateStatus(step.id, WorkflowStepStatus.failed, {
                    error: err instanceof Error ? err.message : String(err),
                });
                this.session.notifyWorkflowStep(featureId, await this.refreshStep(step.id));
                return;
            }
            finally {
                this.session.clearActiveStep(featureId);
            }
        }
        // All remaining steps completed — mark setup as done and persist session ID
        const agentSessionId = await this.sessionRepo.findLatestAgentSessionIdForFeature(featureId);
        await this.appRepo.update(app.id, {
            setupComplete: true,
            ...(agentSessionId ? { agentSessionId } : {}),
        });
    }
    async refreshStep(stepId) {
        const row = await this.stepRepo.findById(stepId);
        if (!row)
            throw new Error(`Workflow step ${stepId} vanished`);
        return row;
    }
};
ResumeApplicationWorkflowUseCase = __decorate([
    injectable(),
    __param(0, inject('IApplicationRepository')),
    __param(1, inject('IWorkflowStepRepository')),
    __param(2, inject('IInteractiveSessionService')),
    __param(3, inject('SendInteractiveMessageUseCase')),
    __param(4, inject('IInteractiveSessionRepository')),
    __metadata("design:paramtypes", [Object, Object, Object, Function, Object])
], ResumeApplicationWorkflowUseCase);
export { ResumeApplicationWorkflowUseCase };
