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 GetAiProjectHealthUseCase = class GetAiProjectHealthUseCase {
    projectRepo;
    workItemRepo;
    cycleRepo;
    stateRepo;
    agentProvider;
    constructor(projectRepo, workItemRepo, cycleRepo, stateRepo, agentProvider) {
        this.projectRepo = projectRepo;
        this.workItemRepo = workItemRepo;
        this.cycleRepo = cycleRepo;
        this.stateRepo = stateRepo;
        this.agentProvider = agentProvider;
    }
    async execute(input) {
        const project = await this.projectRepo.findById(input.projectId);
        if (!project) {
            return { ok: false, error: `Project not found: "${input.projectId}"` };
        }
        const items = await this.workItemRepo.listByProject(input.projectId);
        const cycles = await this.cycleRepo.listByProject(input.projectId);
        const states = await this.stateRepo.listByProject(input.projectId);
        const stateMap = new Map(states.map((s) => [s.id, s]));
        let completedItems = 0;
        let inProgressItems = 0;
        let notStartedItems = 0;
        for (const item of items) {
            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 = items.length;
        const completionPercentage = totalItems > 0 ? (completedItems / totalItems) * 100 : 0;
        const activeCycles = cycles.filter((c) => c.status === 'Active').length;
        let aiSummary = `${project.name}: ${completedItems}/${totalItems} items completed (${Math.round(completionPercentage)}%).`;
        let recommendations;
        try {
            const executor = await this.agentProvider.getExecutor();
            const prompt = [
                'Analyze the following project health data and provide an assessment.',
                'Return a JSON object with:',
                '- overallScore: number 0-100',
                '- narrativeSummary: 2-3 sentence health assessment',
                '- recommendations: array of actionable recommendations',
                '',
                `Project: ${project.name}`,
                `Total work items: ${totalItems}`,
                `Completed: ${completedItems}`,
                `In Progress: ${inProgressItems}`,
                `Not Started: ${notStartedItems}`,
                `Completion: ${Math.round(completionPercentage)}%`,
                `Total cycles: ${cycles.length}`,
                `Active cycles: ${activeCycles}`,
            ]
                .filter(Boolean)
                .join('\n');
            const result = await executor.execute(prompt, {
                outputSchema: {
                    type: 'object',
                    properties: {
                        overallScore: { type: 'number' },
                        narrativeSummary: { type: 'string' },
                        recommendations: { type: 'array', items: { type: 'string' } },
                    },
                },
            });
            const parsed = JSON.parse(result.result);
            if (parsed.narrativeSummary)
                aiSummary = parsed.narrativeSummary;
            if (parsed.recommendations)
                recommendations = parsed.recommendations;
        }
        catch {
            // AI failure is non-fatal — we still return computed metrics
        }
        return {
            ok: true,
            health: {
                projectName: project.name,
                totalItems,
                completedItems,
                inProgressItems,
                notStartedItems,
                completionPercentage,
                activeCycles,
                totalCycles: cycles.length,
                aiSummary,
                recommendations,
            },
        };
    }
};
GetAiProjectHealthUseCase = __decorate([
    injectable(),
    __param(0, inject('IPmProjectRepository')),
    __param(1, inject('IWorkItemRepository')),
    __param(2, inject('ICycleRepository')),
    __param(3, inject('IWorkItemStateRepository')),
    __param(4, inject('IAgentExecutorProvider')),
    __metadata("design:paramtypes", [Object, Object, Object, Object, Object])
], GetAiProjectHealthUseCase);
export { GetAiProjectHealthUseCase };
