/**
 * Aperant Framework Mapper
 * ========================
 *
 * Reference FrameworkMapper implementation per D-06.
 * Translates Aperant-native artifacts (spec.md, implementation_plan.json,
 * build-progress.json, qa_signoff.json) into the 4 Aperant UI shapes.
 *
 * This is the template for community plugin authors.
 */
const FRAMEWORK_ID = 'aperant';
/**
 * Aperant Framework mapper — translates native Aperant artifacts to UI shapes.
 *
 * Each method receives a Map<filename, fileContent> of native artifacts.
 * The mapper parses them and returns the normalized UI shape.
 */
export class AperantFrameworkMapper {
    toContextView(nativeArtifacts) {
        const complexityRaw = nativeArtifacts.get('complexity_assessment.json');
        const contextRaw = nativeArtifacts.get('context.json');
        const requirementsRaw = nativeArtifacts.get('requirements.json');
        let title = 'Untitled';
        let scope = '';
        const decisions = [];
        const deferredItems = [];
        const openQuestions = [];
        const parseErrors = [];
        // Parse complexity assessment
        if (complexityRaw) {
            try {
                const complexity = JSON.parse(complexityRaw);
                title = complexity.title ?? complexity.taskDescription ?? title;
                scope = `Complexity: ${complexity.tier ?? 'unknown'}`;
            }
            catch (e) {
                parseErrors.push(`complexity_assessment.json: ${e instanceof Error ? e.message : String(e)}`);
            }
        }
        // Parse context/requirements if available
        if (requirementsRaw) {
            try {
                const reqs = JSON.parse(requirementsRaw);
                if (Array.isArray(reqs.requirements)) {
                    for (const [i, req] of reqs.requirements.entries()) {
                        decisions.push({
                            id: `REQ-${String(i + 1).padStart(2, '0')}`,
                            summary: typeof req === 'string' ? req : (req.description ?? JSON.stringify(req)),
                        });
                    }
                }
            }
            catch (e) {
                parseErrors.push(`requirements.json: ${e instanceof Error ? e.message : String(e)}`);
            }
        }
        return {
            frameworkId: FRAMEWORK_ID,
            title,
            scope,
            decisions,
            deferredItems,
            openQuestions,
            metadata: {
                complexityAssessment: complexityRaw ? safeJsonParse(complexityRaw) : null,
                context: contextRaw ? safeJsonParse(contextRaw) : null,
                requirements: requirementsRaw ? safeJsonParse(requirementsRaw) : null,
                ...(parseErrors.length > 0 ? { _parseErrors: parseErrors } : {}),
            },
        };
    }
    toPlanView(nativeArtifacts) {
        const planRaw = nativeArtifacts.get('implementation_plan.json');
        const specRaw = nativeArtifacts.get('spec.md');
        let title = 'Implementation Plan';
        const waves = [];
        let totalTasks = 0;
        if (planRaw) {
            try {
                const plan = JSON.parse(planRaw);
                title = plan.title ?? plan.name ?? title;
                // Aperant implementation_plan.json has subtasks array
                const subtasks = plan.subtasks ?? plan.tasks ?? [];
                const tasks = subtasks.map((st, i) => {
                    const t = st;
                    return {
                        id: t.id ?? `task-${i + 1}`,
                        name: t.title ?? t.name ?? `Task ${i + 1}`,
                        status: mapTaskStatus(t.status ?? 'pending'),
                        files: Array.isArray(t.files) ? t.files : [],
                        dependsOn: Array.isArray(t.dependsOn) ? t.dependsOn : [],
                        description: t.description ?? undefined,
                    };
                });
                totalTasks = tasks.length;
                // Single wave for now — Aperant plans don't currently have wave info in the JSON
                if (tasks.length > 0) {
                    waves.push({ waveNumber: 1, tasks });
                }
            }
            catch {
                /* ignore */
            }
        }
        return {
            frameworkId: FRAMEWORK_ID,
            title,
            totalTasks,
            waves,
            metadata: {
                implementationPlan: planRaw ? safeJsonParse(planRaw) : null,
                specMarkdown: specRaw ?? null,
            },
        };
    }
    toProgressView(nativeArtifacts) {
        const progressRaw = nativeArtifacts.get('build-progress.json');
        let progressPercent = 0;
        let totalTasks = 0;
        let completedTasks = 0;
        let failedTasks = 0;
        const recentActivity = [];
        if (progressRaw) {
            try {
                const progress = JSON.parse(progressRaw);
                totalTasks = progress.totalSubtasks ?? progress.total ?? 0;
                completedTasks =
                    progress.completedSubtasks ?? progress.completed ?? 0;
                failedTasks = progress.failedSubtasks ?? progress.failed ?? 0;
                progressPercent = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
                // Parse activity/commits if present
                if (Array.isArray(progress.commits)) {
                    for (const commit of progress.commits) {
                        recentActivity.push({
                            timestamp: commit.timestamp ?? new Date().toISOString(),
                            type: 'commit',
                            message: commit.message ?? 'Unknown commit',
                            commitHash: commit.hash ?? undefined,
                        });
                    }
                }
            }
            catch {
                /* ignore */
            }
        }
        return {
            frameworkId: FRAMEWORK_ID,
            progressPercent,
            totalTasks,
            completedTasks,
            failedTasks,
            currentTask: null,
            recentActivity,
            metadata: {
                buildProgress: progressRaw ? safeJsonParse(progressRaw) : null,
            },
        };
    }
    toVerificationView(nativeArtifacts) {
        const qaRaw = nativeArtifacts.get('qa_signoff.json');
        let status = 'not-run';
        let score = null;
        const dimensions = [];
        const gaps = [];
        const antiPatterns = [];
        if (qaRaw) {
            try {
                const qa = JSON.parse(qaRaw);
                const qaStatus = qa.status ?? qa.decision ?? '';
                status = qaStatus === 'approved' ? 'passed' : qaStatus === 'rejected' ? 'failed' : 'partial';
                // Per D-13: scored dimensions
                if (Array.isArray(qa.dimensions)) {
                    for (const dim of qa.dimensions) {
                        const dimScore = dim.score ?? 0;
                        const threshold = dim.threshold ?? 70;
                        dimensions.push({
                            name: dim.name ?? 'unknown',
                            score: dimScore,
                            threshold,
                            passed: dimScore >= threshold,
                            details: dim.details ?? undefined,
                        });
                    }
                }
                // Compute overall score from dimensions
                if (dimensions.length > 0) {
                    score = Math.round(dimensions.reduce((sum, d) => sum + d.score, 0) / dimensions.length);
                }
                // Parse issues/gaps
                if (Array.isArray(qa.issues)) {
                    for (const issue of qa.issues) {
                        gaps.push({
                            truth: issue.description ?? issue.message ?? 'Unknown issue',
                            reason: issue.reason ?? '',
                            severity: mapSeverity(issue.severity ?? 'minor'),
                            artifacts: Array.isArray(issue.files) ? issue.files : [],
                        });
                    }
                }
                if (Array.isArray(qa.antiPatterns)) {
                    antiPatterns.push(...qa.antiPatterns);
                }
            }
            catch {
                /* ignore */
            }
        }
        return {
            frameworkId: FRAMEWORK_ID,
            status,
            score,
            dimensions,
            gaps,
            antiPatterns,
            metadata: {
                qaSignoff: qaRaw ? safeJsonParse(qaRaw) : null,
            },
        };
    }
}
// =====================================================================
// Helpers
// =====================================================================
function safeJsonParse(raw) {
    try {
        return JSON.parse(raw);
    }
    catch {
        return raw;
    }
}
function mapTaskStatus(status) {
    const map = {
        pending: 'pending',
        'in-progress': 'in-progress',
        in_progress: 'in-progress',
        active: 'in-progress',
        completed: 'completed',
        done: 'completed',
        failed: 'failed',
        error: 'failed',
        skipped: 'skipped',
        skip: 'skipped',
    };
    return map[status.toLowerCase()] ?? 'pending';
}
function mapSeverity(severity) {
    const map = {
        blocker: 'blocker',
        critical: 'blocker',
        major: 'major',
        high: 'major',
        minor: 'minor',
        low: 'minor',
        warning: 'minor',
    };
    return map[severity.toLowerCase()] ?? 'minor';
}
//# sourceMappingURL=aperant-mapper.js.map