'use server';
import { resolve } from '../../lib/server-container.js';
export async function getFeaturePhaseTimings(featureId) {
    if (!featureId.trim()) {
        return { error: 'Feature id is required' };
    }
    try {
        const repo = resolve('IPhaseTimingRepository');
        const phaseTimings = await repo.findByFeatureId(featureId);
        const timings = phaseTimings.map((t) => ({
            agentRunId: t.agentRunId,
            phase: t.phase,
            startedAt: t.startedAt,
            completedAt: t.completedAt,
            durationMs: t.durationMs != null ? Number(t.durationMs) : undefined,
            waitingApprovalAt: t.waitingApprovalAt,
            approvalWaitMs: t.approvalWaitMs != null ? Number(t.approvalWaitMs) : undefined,
            inputTokens: t.inputTokens != null ? Number(t.inputTokens) : undefined,
            outputTokens: t.outputTokens != null ? Number(t.outputTokens) : undefined,
            cacheCreationInputTokens: t.cacheCreationInputTokens != null ? Number(t.cacheCreationInputTokens) : undefined,
            cacheReadInputTokens: t.cacheReadInputTokens != null ? Number(t.cacheReadInputTokens) : undefined,
            costUsd: t.costUsd != null ? Number(t.costUsd) : undefined,
            numTurns: t.numTurns ?? undefined,
            durationApiMs: t.durationApiMs != null ? Number(t.durationApiMs) : undefined,
            exitCode: t.exitCode ?? undefined,
            errorMessage: t.errorMessage ?? undefined,
            prompt: t.prompt ?? undefined,
        }));
        // Read rejection feedback from spec.yaml
        const rejectionFeedback = await readRejectionFeedback(featureId);
        return { timings, rejectionFeedback };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to load phase timings';
        return { error: message };
    }
}
async function readRejectionFeedback(featureId) {
    try {
        const featureRepo = resolve('IFeatureRepository');
        const feature = await featureRepo.findById(featureId);
        if (!feature?.specPath)
            return [];
        const { readFileSync } = await import('node:fs');
        const { join } = await import('node:path');
        const yaml = (await import('js-yaml')).default;
        const specContent = readFileSync(join(feature.specPath, 'spec.yaml'), 'utf-8');
        const spec = yaml.load(specContent);
        if (!Array.isArray(spec?.rejectionFeedback))
            return [];
        return spec.rejectionFeedback.map((entry) => ({
            iteration: Number(entry.iteration ?? 1),
            message: String(entry.message ?? ''),
            phase: entry.phase ? String(entry.phase) : undefined,
            timestamp: entry.timestamp ? String(entry.timestamp) : undefined,
            attachments: Array.isArray(entry.attachments)
                ? entry.attachments.map(String)
                : undefined,
        }));
    }
    catch {
        return [];
    }
}
