// tools/create-spec-tech/ficha-content.ts — FICHA-TECNICA.md content assembly
import { t } from '../../i18n/index.js';
import { formatDiagramsAsMarkdown } from '../../engine/mermaid-generator.js';
import { PLANU_VERSION } from '../../config/version.js';
import { getPlatformSpecSection } from '../create-spec/platform-spec-adapter.js';
import { getMobileArchitectureSections, getDesktopArchitectureSections, } from './section-builders.js';
import { getPlatformContractSection } from '../../engine/platform-engineering/golden-path-generator.js';
import { getHypermediaFichaTecnicaSection } from './constitution.js';
import { getStackTerminology, getArchitectureSections } from './ficha-arch.js';
/**
 * Generate FICHA-TECNICA.md content adapted by scope, with diagrams and architecture sections.
 * SPEC-048: teamScale triggers Platform Contract section for multi-team projects.
 */
export function generateFichaTecnicaContent(spec, description, estimation, knowledge, diagrams, teamScale) {
    const stack = knowledge
        ? `${knowledge.language}${knowledge.framework ? ' / ' + knowledge.framework : ''}`
        : 'Not detected';
    const typesLabel = getStackTerminology(knowledge);
    const archLabel = knowledge ? knowledge.architecture.primary : 'unknown';
    const sections = [
        `# ${spec.id}: ${spec.title} — ${t('sections.metadata')}`,
        '',
        `## ${t('sections.metadata')}`,
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Spec ID | ${spec.id} |`,
        `| Type | ${spec.type} |`,
        `| Scope | ${spec.scope} |`,
        `| Target | ${spec.target} |`,
        `| Difficulty | ${spec.difficulty}/5 |`,
        `| Risk | ${spec.risk} |`,
        `| Stack | ${stack} |`,
        `| Architecture | ${archLabel} |`,
        `| Git Branch | \`${spec.gitBranch}\` |`,
        `| Generated by | Planu v${PLANU_VERSION} |`,
        '',
        `## ${t('sections.estimation')}`,
        '',
        '| Metric | Value |',
        '|--------|-------|',
        `| Dev Hours | ${String(estimation.devHours)}h |`,
        `| Review Hours | ${String(estimation.reviewHours)}h |`,
        `| Recommended Model | ${estimation.recommendedModel} |`,
        `| Tokens (Opus) | ${estimation.tokensOpus.toLocaleString()} |`,
        `| Tokens (Sonnet) | ${estimation.tokensSonnet.toLocaleString()} |`,
        `| API Cost | $${String(estimation.apiCostUsd)} |`,
        `| Human Cost | $${String(estimation.humanCostUsd)} |`,
        `| **Total Cost** | **$${String(estimation.totalCostUsd)}** |`,
        `| Execution Mode | ${estimation.tokenOptimization.mode} |`,
        '',
    ];
    // Scope-specific sections
    if (spec.scope === 'cross-module' || spec.scope === 'architectural') {
        sections.push('## Affected Modules');
        sections.push('');
        sections.push('- (List affected modules and their responsibilities)');
        sections.push('');
    }
    if (spec.scope === 'architectural') {
        sections.push('## Architectural Impact');
        sections.push('');
        sections.push('- **Pattern changes:** (Describe architectural pattern changes)');
        sections.push('- **Breaking changes:** (List any breaking changes)');
        sections.push('- **Migration strategy:** (Describe migration approach)');
        sections.push('');
    }
    // Architecture-specific sections from project knowledge
    sections.push(...getArchitectureSections(knowledge));
    // SPEC-013: Mobile architecture sections
    sections.push(...getMobileArchitectureSections(spec, knowledge));
    // SPEC-014b: Desktop architecture sections
    sections.push(...getDesktopArchitectureSections(spec, knowledge));
    // SPEC-015a: Specialty platform sections (bot, smart-contract, ml, iot)
    sections.push(...getPlatformSpecSection(spec, knowledge));
    // SPEC-043: Backend-first / hypermedia section
    sections.push(...getHypermediaFichaTecnicaSection(knowledge));
    // SPEC-044 TD-P14-02: OTel upgrade policy
    sections.push(...getOtelUpgradePolicySection(knowledge));
    // SPEC-048: Platform Contract section for multi-team projects
    if (teamScale) {
        sections.push(...getPlatformContractSection(teamScale));
    }
    // Interfaces/Types section (skip for trivial)
    if (spec.scope !== 'trivial') {
        sections.push(`## ${typesLabel}`);
        sections.push('');
        sections.push('```typescript');
        sections.push(`// Define ${typesLabel.toLowerCase()} here`);
        sections.push('```');
        sections.push('');
        sections.push(`## ${t('sections.behavior')}`);
        sections.push('');
        sections.push(`### ${t('sections.happyPath')}`);
        sections.push('');
        sections.push('1. (Describe the happy path step by step)');
        sections.push('');
        sections.push(`### ${t('sections.edgeCases')}`);
        sections.push('');
        sections.push('- (List edge cases)');
        sections.push('');
    }
    // Diagrams section
    if (diagrams.length > 0) {
        sections.push('## Diagrams');
        sections.push('');
        sections.push('> 💡 **Tip:** View these diagrams rendered on GitHub, or install the [Markdown Preview Mermaid Support](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid) extension for VS Code.');
        sections.push('');
        sections.push(formatDiagramsAsMarkdown(diagrams));
    }
    // Files section
    sections.push(`## ${t('sections.files')}`);
    sections.push('');
    sections.push(`### ${t('sections.toCreate')}`);
    sections.push('');
    sections.push('- (List files to create)');
    sections.push('');
    sections.push(`### ${t('sections.toModify')}`);
    sections.push('');
    sections.push('- (List files to modify)');
    sections.push('');
    // Verification
    sections.push(`## ${t('sections.verification')}`);
    sections.push('');
    sections.push('- [ ] Implementation matches spec');
    sections.push('- [ ] Tests written and passing');
    sections.push('- [ ] Code reviewed');
    sections.push('- [ ] No regressions');
    sections.push('');
    // Technical notes
    sections.push(`## ${t('sections.technicalNotes')}`);
    sections.push('');
    sections.push(description);
    sections.push('');
    // Post-implementation
    sections.push(`## ${t('sections.postImplementation')}`);
    sections.push('');
    sections.push('| Metric | Estimated | Actual |');
    sections.push('|--------|-----------|--------|');
    sections.push(`| Dev Hours | ${String(estimation.devHours)}h | — |`);
    sections.push(`| Review Hours | ${String(estimation.reviewHours)}h | — |`);
    sections.push(`| API Cost | $${String(estimation.apiCostUsd)} | — |`);
    sections.push(`| Total Cost | $${String(estimation.totalCostUsd)} | — |`);
    sections.push('');
    return sections.join('\n');
}
/**
 * SPEC-044 TD-P14-02: Generate OTel upgrade policy section when project uses OTel.
 * Returns an array of markdown lines if @opentelemetry packages are detected, else [].
 */
export function getOtelUpgradePolicySection(knowledge) {
    if (!knowledge) {
        return [];
    }
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    const allDeps = [...(knowledge.stack ?? []), ...(knowledge.externalServices ?? [])].map((s) => s.toLowerCase());
    const hasOtel = allDeps.some((dep) => dep.includes('opentelemetry'));
    const hasOtelDetection = knowledge.otelDetection?.isInstalled === true;
    if (!hasOtel && !hasOtelDetection) {
        return [];
    }
    return [
        '',
        '## Observability Contract — OTel Upgrade Policy',
        '',
        '> OTel upgrade policy: always update `@opentelemetry/api` + `@opentelemetry/sdk-node` + ' +
            'all `@opentelemetry/*` instrumentation packages in the **same PR**. ' +
            'Never partial upgrades — version skew causes silent instrumentation failures.',
        '',
    ];
}
/**
 * Detect context flags from spec metadata.
 */
export function detectContextFlags(spec, knowledge) {
    const hasDatabase = spec.target === 'database' ||
        spec.target === 'fullstack' ||
        (knowledge?.database !== undefined && knowledge.database !== 'unknown');
    const hasUi = spec.target === 'frontend' ||
        spec.target === 'fullstack' ||
        spec.target === 'ios' ||
        spec.target === 'android';
    // Detect transitions from type (state machines are common in infra/feature)
    const hasTransitions = spec.type === 'infra' || spec.scope === 'architectural';
    return { hasDatabase, hasUi, hasTransitions };
}
//# sourceMappingURL=ficha-content.js.map