"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextRenderer = void 0;
/**
 * ContextRenderer: Utility to render human-readable Markdown from the LivingContext JSON.
 */
class ContextRenderer {
    static renderPRD(context) {
        const features = this.renderFeaturesSnippet(context);
        const edgeCases = this.renderEdgeCasesSnippet(context);
        const functional = context.phases?.functional_summary || {};
        const intent = context.phases?.design_intent || {};
        const prd = context.prd || {};
        const title = functional.app_name || prd.title || context.metadata?.projectConfig?.name || "The App";
        const purpose = functional.core_purpose || prd.problemStatement || "To provide high-quality AI-driven development capabilities.";
        const goals = functional.key_features || prd.goals || ["Automate development workflows", "Enhance context awareness"];
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Product Requirements Document

## Project Overview
**Project Name:** ${title}
**Description:** ${context.metadata?.projectConfig?.description || "A feature-rich application"}

## Core Purpose
${purpose}

## Goals
${goals.map((g) => `- ${g}`).join("\n")}

${features}

${edgeCases}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderFeaturesSnippet(context) {
        if (!context.features || !Array.isArray(context.features))
            return "";
        return `
## Key Features
${context.features.map(f => `
### ${f.name || "Unnamed Feature"} (${(f.priority || "medium").toUpperCase()})
**Description:** ${f.description || "N/A"}
**Value:** ${f.userValue || "N/A"}
**Acceptance Criteria:**
${f.acceptanceCriteria?.map(ac => `- [ ] ${ac}`).join("\n") || "- N/A"}
`).join("\n---")}
`;
    }
    static renderEdgeCasesSnippet(context) {
        if (!context.edgeCases || !Array.isArray(context.edgeCases))
            return "";
        return `
## Edge Cases & Mitigations
${context.edgeCases.map(ec => `
- **[${ec.category || "General"}] ${ec.description || "N/A"}**: ${ec.mitigation || "N/A"}`).join("\n")}
`;
    }
    static renderFeatures(context) {
        if (!context.features || !Array.isArray(context.features))
            return "# Product Features\n\nNo features defined yet.";
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Product Features

${context.features.map(f => `
### ${f.name || "Unnamed Feature"} (${(f.priority || "medium").toUpperCase()})
**Description:** ${f.description || "N/A"}
**Value:** ${f.userValue || "N/A"}
**Acceptance Criteria:**
${f.acceptanceCriteria?.map(ac => `- [ ] ${ac}`).join("\n") || "- N/A"}
**Dependencies:** ${f.dependencies?.join(", ") || "None"}
`).join("\n---")}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderTechnicalSpecs(context) {
        if (!context.specs)
            return "# Technical Specifications\n\nNo technical specifications defined yet.";
        const types = context.brain?.types || { entities: [], shared: [] };
        const typesSnippet = this.renderTypesSnippet(types);
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Technical Specifications

## Architecture
${context.specs.architecture || "Standard modern web architecture"}

## Technology Stack
- **Frontend:** ${context.specs.techStack?.frontend?.join(", ") || "Next.js, Tailwind CSS"}
- **Backend:** ${context.specs.techStack?.backend?.join(", ") || "Next.js API Routes"}
- **Database:** ${context.specs.techStack?.database?.join(", ") || "Local storage"}

${typesSnippet}

## API Endpoints
${context.specs.apiEndpoints?.map(e => `- **${e.method} ${e.path}**: ${e.description} (Auth: ${e.authRequired ? "Yes" : "No"})`).join("\n") || "None defined"}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderTypesSnippet(types) {
        if (!types.entities?.length && !types.shared?.length)
            return "";
        return `
## Type Guide & Data Entities
${(types.entities || []).map((e) => `
### ${e.name}
${e.description}
\`\`\`typescript
${e.schema}
\`\`\`
`).join("\n")}

### Shared Utility Types
${(types.shared || []).map((s) => `- **${s.name}**: ${s.description}`).join("\n")}
`;
    }
    static renderUserFlows(context) {
        if (!context.flows || !Array.isArray(context.flows))
            return "# User Flows\n\nNo user flows defined yet.";
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# User Flows

${context.flows.map(f => `
### ${f.name || "Unnamed Flow"}
**Description:** ${f.description || "N/A"}
**Actors:** ${f.actors?.join(", ") || "User"}
**Steps:**
${f.steps?.map((s, i) => `${i + 1}. ${s}`).join("\n") || "None defined"}
`).join("\n---")}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderEdgeCases(context) {
        if (!context.edgeCases || !Array.isArray(context.edgeCases))
            return "# Edge Cases\n\nNo edge cases defined yet.";
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Edge Cases

${context.edgeCases.map(ec => `
### [${ec.category || "General"}] ${ec.description || "N/A"}
**Mitigation:** ${ec.mitigation || "N/A"}
`).join("\n---")}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderComponentList(context) {
        if (!context.components || !Array.isArray(context.components))
            return "# Component Architecture\n\nNo components defined yet.";
        const groups = {};
        context.components.forEach(c => {
            const g = c.group || "Uncategorized";
            if (!groups[g])
                groups[g] = [];
            groups[g].push(c);
        });
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Component Architecture

${Object.entries(groups).map(([group, comps]) => `
## ${group}
${comps.map(c => `- **${c.name}**: ${c.description || "N/A"} (${c.type || "UI Component"}) [Status: ${c.status || "Planned"}]`).join("\n")}
`).join("\n")}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderTypesGuide(context) {
        const types = context.brain?.types || { entities: [], shared: [] };
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Architecture & Type Guide

## Core Entities
${(types.entities || []).map((e) => `
### ${e.name}
${e.description}
\`\`\`typescript
${e.schema}
\`\`\`
`).join("\n") || "None defined"}

## Shared Types
${(types.shared || []).map((s) => `
### ${s.name}
${s.description}
\`\`\`typescript
${s.schema}
\`\`\`
`).join("\n") || "None defined"}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderBrandGuide(context) {
        const brief = context.phases?.design_brief || {};
        const brand = context.brain?.brand || brief || { theme: "light", colors: {}, typography: {}, designPrinciples: [] };
        const intent = context.phases?.design_intent || {};
        const designPrinciples = brand.designPrinciples || intent.design_anchors || [];
        const comps = this.renderComponentList(context);
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Brand & Design Guidelines

## Visual Identity
**Theme:** ${brand.theme || "light"}
**Primary Color:** ${brand.colors?.primary || brand.primary_color || "N/A"}
**Background:** ${brand.colors?.background || "N/A"}

## Design Principles
${designPrinciples.map((p) => `- ${p}`).join("\n") || "N/A"}

${comps}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderEvolutionHistory(context) {
        const history = context.phases?.evolution_history || { decision_log: [], surprises_discoveries: [], milestones: [] };
        return `> [!IMPORTANT]
> **READ-ONLY VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Evolution History & Decision Log

## Decision Log
${history.decision_log?.map((d) => `
### ${d.decision} (${d.date})
**Rationale:** ${d.rationale}
**Author:** ${d.author || "Agent"}
`).join("\n---") || "No decisions recorded yet."}

## Surprises & Discoveries
${history.surprises_discoveries?.map((s) => `
- **Observation:** ${s.observation}
  **Evidence:** ${s.evidence}
  ${s.impact ? `**Impact:** ${s.impact}` : ""}
`).join("\n") || "No discoveries recorded yet."}

## Milestones & Outcomes
${history.milestones?.map((m) => `
### ${m.outcome} [${m.status.toUpperCase()}]
**Proof:** ${m.proof}
**ID:** ${m.id} ${m.timestamp ? `| **Achieved:** ${m.timestamp}` : ""}
`).join("\n---") || "No milestones defined yet."}

${history.retrospective ? `
## Retrospective
${history.retrospective}
` : ""}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderSpecRequirements(specName, spec) {
        const reqs = spec.requirements || { userStory: "", glossary: [], acceptanceCriteria: [] };
        const glossarySnippet = reqs.glossary?.length
            ? `\n## Glossary\n\n| Term | Definition |\n|---|---|\n${reqs.glossary.map((g) => `| **${g.term}** | ${g.definition} |`).join("\n")}`
            : "";
        const criteriaSnippet = reqs.acceptanceCriteria?.length
            ? `\n## Acceptance Criteria (EARS Patterns)\n\n${reqs.acceptanceCriteria.map((ac) => `### [${ac.id}] ${ac.pattern.toUpperCase()}\n- **Requirement:** ${ac.statement}\n${ac.rationale ? `- **Rationale:** ${ac.rationale}\n` : ""}`).join("\n")}`
            : "\n*No acceptance criteria defined yet.*";
        return `> [!IMPORTANT]
> **READ-ONLY SPECIFICATION VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Specification: ${spec.displayName || specName} — Requirements

## User Story
${reqs.userStory || "*No user story defined yet.*"}
${glossarySnippet}
${criteriaSnippet}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderSpecDesign(specName, spec) {
        const design = spec.design || { architectureDecisions: [], components: [], correctnessProperties: [] };
        const decisionsSnippet = design.architectureDecisions?.length
            ? `\n## Architectural Decisions\n\n${design.architectureDecisions.map((d) => `### [${d.id}] ${d.decision}\n- **Rationale:** ${d.rationale}\n${d.alternativesConsidered?.length ? `- **Alternatives:** ${d.alternativesConsidered.join(", ")}\n` : ""}`).join("\n")}`
            : "";
        const componentsSnippet = design.components?.length
            ? `\n## Technical Components\n\n${design.components.map((c) => `### ${c.name}\n- **Description:** ${c.description}\n${c.filePath ? `- **Path:** \`${c.filePath}\`\n` : ""}${c.props?.length ? `- **Properties:**\n${c.props.map((p) => `  - \`${p.name}\` (${p.type}): ${p.description}`).join("\n")}\n` : ""}${c.apisUsed?.length ? `- **APIs Used:** ${c.apisUsed.join(", ")}\n` : ""}`).join("\n")}`
            : "";
        const propertiesSnippet = design.correctnessProperties?.length
            ? `\n## Core Correctness Properties (Testing Invariants)\n\n| ID | Requirement | Pattern | Description |\n|---|---|---|---|\n${design.correctnessProperties.map((p) => `| **${p.id}** | [${p.requirementId}](#${p.requirementId.toLowerCase()}) | *${p.pattern}* | ${p.description} |`).join("\n")}`
            : "";
        return `> [!IMPORTANT]
> **READ-ONLY SPECIFICATION VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Specification: ${spec.displayName || specName} — Technical Design

${decisionsSnippet}
${componentsSnippet}
${propertiesSnippet}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
    static renderSpecTasks(specName, spec) {
        const tasks = spec.tasks || [];
        const completed = tasks.filter((t) => t.status === "complete").length;
        const total = tasks.length;
        const percent = total > 0 ? Math.round((completed / total) * 100) : 0;
        // Create progress bar
        const filled = Math.round((percent / 100) * 15);
        const empty = 15 - filled;
        const progressBar = "█".repeat(filled) + "░".repeat(empty);
        const tasksSnippet = tasks.length
            ? `\n## Development Checklist\n\n${tasks.map((t) => {
                const statusIcon = t.status === "complete" ? "[x]" : t.status === "failed" ? "[!]" : "[ ]";
                const statusText = t.status.toUpperCase();
                return `### ${statusIcon} ${t.id}: ${t.description} — \`${statusText}\`
${t.dependencies?.length ? `- **Requires:** ${t.dependencies.map((d) => `\`${d}\``).join(", ")}\n` : ""}- **Verification Steps:**
${t.verificationSteps.map((step) => `  - [ ] ${step}`).join("\n")}
`;
            }).join("\n")}`
            : "\n*No tasks generated yet.*";
        return `> [!IMPORTANT]
> **READ-ONLY SPECIFICATION VIEW**: This file is an export from \`context.json\`. 
> Do NOT edit this file directly. Any manual changes will be overwritten.
> **Source of Truth**: [\`.mycontext/context.json\`](file://./.mycontext/context.json)

# Specification: ${spec.displayName || specName} — Implementation Plan & Tasks

## Project Progress
**Status:** ${spec.currentPhase.toUpperCase()}
**Completion Percentage:** ${percent}% \`${progressBar}\`

${tasksSnippet}

---
*Generated by MyContext CLI - Living Brain JSON Source*
`;
    }
}
exports.ContextRenderer = ContextRenderer;
//# sourceMappingURL=contextRenderer.js.map