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 { StateGroup } from '../../../domain/generated/output.js';
let GetAiCycleSummaryUseCase = class GetAiCycleSummaryUseCase {
    cycleRepo;
    workItemRepo;
    stateRepo;
    agentProvider;
    constructor(cycleRepo, workItemRepo, stateRepo, agentProvider) {
        this.cycleRepo = cycleRepo;
        this.workItemRepo = workItemRepo;
        this.stateRepo = stateRepo;
        this.agentProvider = agentProvider;
    }
    async execute(input) {
        const cycle = await this.cycleRepo.findById(input.cycleId);
        if (!cycle) {
            return { ok: false, error: `Cycle not found: "${input.cycleId}"` };
        }
        const workItemIds = await this.cycleRepo.getWorkItemIds(input.cycleId);
        const states = await this.stateRepo.listByProject(cycle.projectId);
        const stateMap = new Map(states.map((s) => [s.id, s]));
        const items = await Promise.all(workItemIds.map((id) => this.workItemRepo.findById(id)));
        const validItems = items.filter((i) => i != null);
        let completedItems = 0;
        let inProgressItems = 0;
        let notStartedItems = 0;
        for (const item of validItems) {
            const state = stateMap.get(item.stateId);
            if (!state)
                continue;
            switch (state.stateGroup) {
                case StateGroup.Completed:
                    completedItems++;
                    break;
                case StateGroup.Started:
                    inProgressItems++;
                    break;
                default:
                    notStartedItems++;
                    break;
            }
        }
        const totalItems = validItems.length;
        const completionPercentage = totalItems > 0 ? (completedItems / totalItems) * 100 : 0;
        let aiSummary = `${cycle.name}: ${completedItems}/${totalItems} items completed (${Math.round(completionPercentage)}%).`;
        let risks;
        try {
            const executor = await this.agentProvider.getExecutor();
            const prompt = [
                'Analyze the following sprint/cycle data and provide a concise progress summary.',
                'Return a JSON object with:',
                '- summary: a natural language progress summary (2-3 sentences)',
                '- risks: array of risk strings (empty if none)',
                '',
                `Cycle: ${cycle.name}`,
                `Status: ${cycle.status}`,
                cycle.startDate ? `Start: ${new Date(cycle.startDate).toISOString().split('T')[0]}` : '',
                cycle.endDate ? `End: ${new Date(cycle.endDate).toISOString().split('T')[0]}` : '',
                `Total items: ${totalItems}`,
                `Completed: ${completedItems}`,
                `In Progress: ${inProgressItems}`,
                `Not Started: ${notStartedItems}`,
                `Completion: ${Math.round(completionPercentage)}%`,
            ]
                .filter(Boolean)
                .join('\n');
            const result = await executor.execute(prompt, {
                outputSchema: {
                    type: 'object',
                    properties: {
                        summary: { type: 'string' },
                        risks: { type: 'array', items: { type: 'string' } },
                    },
                },
            });
            const parsed = JSON.parse(result.result);
            if (parsed.summary)
                aiSummary = parsed.summary;
            if (parsed.risks)
                risks = parsed.risks;
        }
        catch {
            // AI failure is non-fatal — we still return computed metrics
        }
        return {
            ok: true,
            summary: {
                cycleName: cycle.name,
                totalItems,
                completedItems,
                inProgressItems,
                notStartedItems,
                completionPercentage,
                aiSummary,
                risks,
            },
        };
    }
};
GetAiCycleSummaryUseCase = __decorate([
    injectable(),
    __param(0, inject('ICycleRepository')),
    __param(1, inject('IWorkItemRepository')),
    __param(2, inject('IWorkItemStateRepository')),
    __param(3, inject('IAgentExecutorProvider')),
    __metadata("design:paramtypes", [Object, Object, Object, Object])
], GetAiCycleSummaryUseCase);
export { GetAiCycleSummaryUseCase };
