import {
    BugRecord,
    DecisionRecord,
    DevelopmentLog,
    DiscussionRecord,
    PlanningDocument,
    ProjectProfile,
    RetrospectiveRecord
} from './types';

const list = (items: string[] | undefined, fallback: string = 'Not captured yet.') => {
    if (!items || items.length === 0) return fallback;
    return items.map(item => `- ${item}`).join('\n');
};

const dateOnly = (iso?: string) => (iso || new Date().toISOString()).slice(0, 10);

export function renderProjectReadme(profile: ProjectProfile): string {
    return [
        `# ${profile.projectName} Chronicle Records`,
        '',
        '## Project',
        `- ID: ${profile.projectId}`,
        `- Root: ${profile.projectRoot || 'Not set'}`,
        `- Record root: ${profile.recordRoot}`,
        `- Detail level: ${profile.detailLevel}`,
        '',
        '## Purpose',
        profile.corePurpose || profile.description || 'Not captured yet.',
        '',
        '## Folders',
        '- `planning/`',
        '- `discussions/`',
        '- `decisions/`',
        '- `development/`',
        '- `bugs/`',
        '- `retrospectives/`'
    ].join('\n');
}

export function renderProjectProfile(profile: ProjectProfile): string {
    return [
        '# Project Profile',
        '',
        '## Project Name',
        profile.projectName,
        '',
        '## Description',
        profile.description || 'Not captured yet.',
        '',
        '## Project Root',
        profile.projectRoot || 'Not set',
        '',
        '## Record Root',
        profile.recordRoot,
        '',
        '## Core Purpose',
        profile.corePurpose || 'Not captured yet.',
        '',
        '## Target Users',
        list(profile.targetUsers),
        '',
        '## Avoid Directions',
        list(profile.avoidDirections),
        '',
        '## Record Detail Level',
        profile.detailLevel,
        '',
        '## Created',
        profile.createdAt,
        '',
        '## Updated',
        profile.updatedAt
    ].join('\n');
}

export function renderTimelineSeed(profile: ProjectProfile): string {
    return [
        '# Project Timeline',
        '',
        `## ${dateOnly(profile.createdAt)}`,
        `- Project Chronicle record folder initialized for ${profile.projectName}.`
    ].join('\n');
}

export function renderPlanningDocument(doc: PlanningDocument): string {
    return [
        `# Feature Plan: ${doc.featureName}`,
        '',
        '## 1. Feature Name',
        doc.featureName,
        '',
        '## 2. Reason',
        doc.purpose,
        '',
        '## 3. Original User Request',
        doc.sourceRequest || 'Not captured yet.',
        '',
        '## 4. Interpreted User Intent',
        doc.userIntent,
        '',
        '## 5. Background',
        doc.background,
        '',
        '## 6. Scope',
        list(doc.scope),
        '',
        '## 7. Out Of Scope',
        list(doc.outOfScope),
        '',
        '## 8. Development Direction',
        doc.developmentDirection,
        '',
        '## 9. Dependency Strategy',
        doc.dependencyStrategy,
        '',
        '## 10. Expected Value',
        doc.expectedValue,
        '',
        '## 11. Success Criteria',
        list(doc.successCriteria),
        '',
        '## 12. Developer Instruction',
        doc.developerInstruction
    ].join('\n');
}

export function renderDiscussionRecord(record: DiscussionRecord): string {
    const questions = record.questions.length
        ? record.questions.map((q, index) => [
            `### Question ${index + 1}`,
            q.question,
            '',
            '### Reason',
            q.reason,
            '',
            '### Expected Information',
            q.expectedInformation,
            '',
            '### Impact On Decision',
            q.impactOnDecision,
            '',
            q.userAnswer ? `### User Answer\n${q.userAnswer}` : '',
            q.result ? `### Result\n${q.result}` : ''
        ].filter(Boolean).join('\n')).join('\n\n')
        : 'No explicit question was captured.';

    return [
        `# Discussion: ${record.title}`,
        '',
        '## User Request Summary',
        record.userRequest,
        '',
        '## Interpreted Intent',
        record.interpretedIntent,
        '',
        '## Questions',
        questions,
        '',
        '## Main Discussion',
        list(record.discussions),
        '',
        '## Decisions',
        record.decisions.length
            ? record.decisions.map(decision => `- ${decision.title}: ${decision.decision}`).join('\n')
            : 'No decisions captured yet.'
    ].join('\n');
}

export function renderDecisionRecord(record: DecisionRecord): string {
    return [
        `# ADR: ${record.title}`,
        '',
        '## Status',
        record.status,
        '',
        '## Context',
        record.context,
        '',
        '## Decision',
        record.decision,
        '',
        '## Reason',
        record.reason,
        '',
        '## Alternatives',
        list(record.alternatives),
        '',
        '## Consequences',
        list(record.consequences)
    ].join('\n');
}

export function renderDevelopmentLog(log: DevelopmentLog): string {
    return [
        `# Development Log: ${log.featureName}`,
        '',
        '## Purpose',
        log.purpose,
        '',
        '## Implementation Summary',
        log.implementationSummary,
        '',
        '## Architecture',
        log.architecture,
        '',
        '## Changed Files',
        list(log.changedFiles),
        '',
        '## Dependency Notes',
        log.dependencyNotes,
        '',
        '## Bugs',
        log.bugs.length ? log.bugs.map(bug => `- ${bug.title}: ${bug.symptom}`).join('\n') : 'No bugs recorded.',
        '',
        '## Lessons',
        list(log.lessons)
    ].join('\n');
}

export function renderBugRecord(record: BugRecord): string {
    return [
        `# Bug: ${record.title}`,
        '',
        '## Date',
        dateOnly(record.createdAt),
        '',
        '## Symptom',
        record.symptom,
        '',
        '## Cause',
        record.cause,
        '',
        '## Fix',
        record.fix,
        '',
        '## Prevention',
        record.prevention
    ].join('\n');
}

export function renderRetrospective(record: RetrospectiveRecord): string {
    return [
        `# Retrospective: ${record.title}`,
        '',
        '## Summary',
        record.summary,
        '',
        '## Went Well',
        list(record.wentWell),
        '',
        '## To Improve',
        list(record.toImprove),
        '',
        '## Next Actions',
        list(record.nextActions)
    ].join('\n');
}
