import { ti } from '../i18n/index.js';
import { specStore, knowledgeStore } from '../storage/index.js';
import { dirname } from 'node:path';
import { readLastModifiedTimestamp, formatRelativeDate } from '../engine/spec-changelog/index.js';
export async function handleListSpecs(params) {
    const { projectId, status, type } = params;
    try {
        // Verify project exists
        const knowledge = await knowledgeStore.getKnowledge(projectId);
        if (!knowledge) {
            return {
                content: [{ type: 'text', text: ti('project.notFound', {}) }],
                isError: true,
            };
        }
        // Get all specs
        let specs = await specStore.listSpecs(projectId);
        // Apply filters
        if (status) {
            specs = specs.filter((s) => s.status === status);
        }
        if (type) {
            specs = specs.filter((s) => s.type === type);
        }
        // Build summary statistics
        const allSpecs = await specStore.listSpecs(projectId);
        const statusCounts = {};
        const typeCounts = {};
        for (const s of allSpecs) {
            statusCounts[s.status] = (statusCounts[s.status] ?? 0) + 1;
            typeCounts[s.type] = (typeCounts[s.type] ?? 0) + 1;
        }
        // Calculate aggregated estimation
        const totalDevHours = specs.reduce((sum, s) => sum + s.estimation.devHours, 0);
        const totalReviewHours = specs.reduce((sum, s) => sum + s.estimation.reviewHours, 0);
        const totalCostUsd = specs.reduce((sum, s) => sum + s.estimation.totalCostUsd, 0);
        // Fetch last modified timestamps from changelogs (AC-09)
        const lastModifiedMap = new Map();
        await Promise.all(specs.map(async (s) => {
            if (!s.specPath) {
                return;
            }
            const specDir = dirname(s.specPath);
            const timestamp = await readLastModifiedTimestamp(specDir);
            if (timestamp) {
                lastModifiedMap.set(s.id, formatRelativeDate(timestamp));
            }
        }));
        // SPEC-091: Auto-suggest Agent Teams when 3+ approved specs exist
        const approvedSpecs = allSpecs.filter((s) => s.status === 'approved');
        let teamSuggestion = null;
        if (approvedSpecs.length >= 3) {
            teamSuggestion = {
                recommended: true,
                reason: `${String(approvedSpecs.length)} approved specs can be implemented in parallel using Agent Teams.`,
                templateId: 'parallel-specs',
                teamSize: Math.min(approvedSpecs.length, 5),
                specs: approvedSpecs.map((s) => s.id),
                toolCalls: [
                    `plan_team_distribution({ projectId: "${projectId}", specIds: [${approvedSpecs.map((s) => `"${s.id}"`).join(', ')}], template: "parallel-specs" })`,
                ],
            };
        }
        const result = {
            projectId,
            filters: {
                status: status ?? 'all',
                type: type ?? 'all',
            },
            count: specs.length,
            totalCount: allSpecs.length,
            specs: specs.map((s) => ({
                id: s.id,
                title: s.title,
                type: s.type,
                scope: s.scope,
                status: s.status,
                difficulty: s.difficulty,
                risk: s.risk,
                target: s.target,
                tags: s.tags,
                gitBranch: s.gitBranch,
                estimation: {
                    devHours: s.estimation.devHours,
                    totalCostUsd: s.estimation.totalCostUsd,
                },
                createdAt: s.createdAt,
                updatedAt: s.updatedAt,
                lastModified: lastModifiedMap.get(s.id) ?? '\u2014',
            })),
            summary: {
                byStatus: statusCounts,
                byType: typeCounts,
                totalDevHours: Math.round(totalDevHours * 10) / 10,
                totalReviewHours: Math.round(totalReviewHours * 10) / 10,
                totalCostUsd: Math.round(totalCostUsd * 100) / 100,
            },
            teamSuggestion,
            message: ti('tools.list_specs.success', { count: String(specs.length) }),
        };
        return {
            content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
            isError: true,
        };
    }
}
//# sourceMappingURL=list-specs.js.map