/**
 * ADR-PIPELINE-094 Decision 8 — Phase 4 local fallback generator.
 *
 * Produces minimal Architecture Decision Records, a domain model, and a
 * bounded-contexts manifest from Phase-1 simulator consensus. Output is
 * tagged `quality: degraded` and is sufficient to satisfy the Phase 5a
 * gate's any-of clause (the prompt generator's Phase-1 fallback branch
 * also accepts these as inputs).
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
import { readPhase1Consensus } from './phase1-consensus-reader.js';
/**
 * Run the Phase-4 fallback. Writes:
 *   - phase4/adrs/ADR-001-system-decomposition.md
 *   - phase4/adrs/ADR-002-integration-surface.md
 *   - phase4/adrs/adr-index.json
 *   - phase4/ddd/bounded-contexts.json
 *   - phase4/ddd/domain-model.md
 *   - engineering/architecture-decisions.md (consensus surface form)
 */
export function runPhase4LocalFallback(runDir) {
    const consensus = readPhase1Consensus(runDir);
    if (!consensus) {
        return {
            success: false,
            filesWritten: [],
            reason: 'no-phase1-consensus',
            message: 'Phase-4 local fallback: no Phase-1 consensus on disk',
        };
    }
    const filesWritten = [];
    try {
        // ── ADRs ──────────────────────────────────────────────────────────────
        const adrsDir = path.join(runDir, 'phase4', 'adrs');
        fs.mkdirSync(adrsDir, { recursive: true });
        const adrs = buildMinimalADRs(consensus);
        for (const adr of adrs) {
            const filename = `ADR-${String(adr.number).padStart(3, '0')}-${adr.slug}.md`;
            fs.writeFileSync(path.join(adrsDir, filename), adr.body, 'utf8');
            filesWritten.push(`phase4/adrs/${filename}`);
        }
        fs.writeFileSync(path.join(adrsDir, 'adr-index.json'), JSON.stringify({ generator: 'local-fallback', quality: 'degraded', adrs: adrs.map(a => ({
                id: `ADR-${String(a.number).padStart(3, '0')}`, title: a.title, file: `ADR-${String(a.number).padStart(3, '0')}-${a.slug}.md`,
            })) }, null, 2), 'utf8');
        filesWritten.push('phase4/adrs/adr-index.json');
        // ── DDD ───────────────────────────────────────────────────────────────
        const dddDir = path.join(runDir, 'phase4', 'ddd');
        fs.mkdirSync(dddDir, { recursive: true });
        const boundedContexts = buildMinimalBoundedContexts(consensus);
        fs.writeFileSync(path.join(dddDir, 'bounded-contexts.json'), JSON.stringify(boundedContexts, null, 2), 'utf8');
        filesWritten.push('phase4/ddd/bounded-contexts.json');
        fs.writeFileSync(path.join(dddDir, 'domain-model.md'), buildDomainModelMarkdown(consensus, boundedContexts), 'utf8');
        filesWritten.push('phase4/ddd/domain-model.md');
        // ── Engineering surface (mirror) ──────────────────────────────────────
        const engDir = path.join(runDir, 'engineering');
        fs.mkdirSync(engDir, { recursive: true });
        fs.writeFileSync(path.join(engDir, 'architecture-decisions.md'), buildEngineeringConsensusMarkdown(consensus, adrs), 'utf8');
        filesWritten.push('engineering/architecture-decisions.md');
    }
    catch (err) {
        return {
            success: false,
            filesWritten,
            reason: 'write-error',
            message: `Phase-4 local fallback: write failed — ${err.message}`,
        };
    }
    return {
        success: true,
        filesWritten,
        message: `Phase-4 local fallback: wrote ${filesWritten.length} architecture artifacts (degraded)`,
    };
}
function buildMinimalADRs(c) {
    const decisionMemo = c.decisionMemo?.trim() ?? '';
    // ADR-001 — System decomposition. Always emitted as the seed decision.
    const adr1Body = [
        '---',
        'id: ADR-001',
        'title: System Decomposition (Phase-1 fallback)',
        'status: Proposed',
        'quality: degraded',
        'generator: local-fallback',
        'source: phase1-consensus',
        '---',
        '',
        '# ADR-001: System Decomposition',
        '',
        '> Generated by local fallback (Ruflo unavailable). Quality: **degraded**.',
        '',
        '## Context',
        '',
        decisionMemo || 'Phase-1 simulator consensus indicates a single-service decomposition is appropriate for this scenario; bounded contexts are inferred from the brief at implementation time.',
        '',
        '## Decision',
        '',
        'Single-service architecture with three internal layers — analysis, decision, integration — separated by explicit interfaces. Persistence and external IO live behind narrow ports so the analysis and decision layers stay testable without a network or database.',
        '',
        '## Consequences',
        '',
        '- **Positive:** Minimal coordination cost; fast to ship; easy to reason about.',
        '- **Negative:** No bounded-context boundaries enforced at the module-system level; future split requires refactoring.',
        '',
    ].join('\n');
    // ADR-002 — Integration surface. Always emitted because most scenarios
    // we serve involve at least one external surface (ERP, webhook, etc.).
    const adr2Body = [
        '---',
        'id: ADR-002',
        'title: Integration Surface (Phase-1 fallback)',
        'status: Proposed',
        'quality: degraded',
        'generator: local-fallback',
        'source: phase1-consensus',
        '---',
        '',
        '# ADR-002: Integration Surface',
        '',
        '> Generated by local fallback (Ruflo unavailable). Quality: **degraded**.',
        '',
        '## Context',
        '',
        'External integrations (ERP, REST APIs, webhooks) require an explicit surface so the integration layer is testable without live endpoints.',
        '',
        '## Decision',
        '',
        'Define one `IntegrationPort` interface per external surface. Adapters live under `src/integration/`. Adapters MUST validate inbound payloads, propagate correlation IDs end-to-end, and surface meaningful errors as typed `AppError` subclasses.',
        '',
        '## Consequences',
        '',
        '- **Positive:** Clear contract for future adapters; easy to mock in tests.',
        '- **Negative:** One interface per surface adds boilerplate when surfaces are simple.',
        '',
    ].join('\n');
    return [
        { number: 1, slug: 'system-decomposition', title: 'System Decomposition (Phase-1 fallback)', body: adr1Body },
        { number: 2, slug: 'integration-surface', title: 'Integration Surface (Phase-1 fallback)', body: adr2Body },
    ];
}
function buildMinimalBoundedContexts(_c) {
    return {
        generator: 'local-fallback',
        quality: 'degraded',
        contexts: [
            {
                name: 'Analysis',
                description: 'Pure functions that compute analytical outputs from inbound data.',
                aggregates: ['AnalysisResult'],
                layer: 'core',
            },
            {
                name: 'Decision',
                description: 'Decision-making layer — consumes Analysis output and emits actionable recommendations.',
                aggregates: ['Decision'],
                layer: 'core',
            },
            {
                name: 'Integration',
                description: 'Outbound integration with external surfaces (ERP, webhook).',
                aggregates: ['IntegrationCall', 'IntegrationReceipt'],
                layer: 'edge',
            },
        ],
        contextMap: [
            { upstream: 'Analysis', downstream: 'Decision', relationship: 'Customer-Supplier' },
            { upstream: 'Decision', downstream: 'Integration', relationship: 'Open Host Service' },
        ],
        ubiquitousLanguage: [
            { term: 'AnalysisResult', definition: 'Output of the Analysis layer; immutable record of computed metrics.' },
            { term: 'Decision', definition: 'Output of the Decision layer; recommended next action with rationale.' },
            { term: 'IntegrationCall', definition: 'A request emitted to an external surface with a correlation ID.' },
        ],
    };
}
function buildDomainModelMarkdown(c, m) {
    const lines = [];
    lines.push('---');
    lines.push('title: Domain Model (Phase-1 fallback)');
    lines.push('quality: degraded');
    lines.push('generator: local-fallback');
    lines.push('---');
    lines.push('');
    lines.push('# Domain Model');
    lines.push('');
    lines.push('> Generated by local fallback (Ruflo unavailable). Quality: **degraded**.');
    lines.push('');
    lines.push('## Bounded Contexts');
    lines.push('');
    for (const ctx of m.contexts) {
        lines.push(`### ${ctx.name} (${ctx.layer})`);
        lines.push('');
        lines.push(ctx.description);
        lines.push('');
        lines.push(`**Aggregates:** ${ctx.aggregates.join(', ')}`);
        lines.push('');
    }
    lines.push('## Context Map');
    lines.push('');
    for (const r of m.contextMap) {
        lines.push(`- ${r.upstream} → ${r.downstream} (${r.relationship})`);
    }
    lines.push('');
    if (c.executiveSummary) {
        lines.push('## Source — Phase-1 Executive Summary');
        lines.push('');
        lines.push(c.executiveSummary.trim());
        lines.push('');
    }
    return lines.join('\n');
}
function buildEngineeringConsensusMarkdown(c, adrs) {
    const lines = [];
    lines.push('---');
    lines.push('title: Architecture Decisions (engineering consensus, Phase-1 fallback)');
    lines.push('quality: degraded');
    lines.push('generator: local-fallback');
    lines.push('---');
    lines.push('');
    lines.push('# Architecture Decisions — Consensus');
    lines.push('');
    lines.push('> Generated by local fallback (Ruflo unavailable). Quality: **degraded**.');
    lines.push('');
    for (const adr of adrs) {
        lines.push(`## ADR-${String(adr.number).padStart(3, '0')}: ${adr.title}`);
        lines.push('');
        // Strip the frontmatter and reuse the prose body.
        const body = adr.body.replace(/^---[\s\S]*?---\n*/, '').trim();
        lines.push(body);
        lines.push('');
    }
    if (c.decisionMemo) {
        lines.push('## Phase-1 Decision Memo (raw)');
        lines.push('');
        lines.push(c.decisionMemo.trim());
        lines.push('');
    }
    return lines.join('\n');
}
//# sourceMappingURL=phase4-local-fallback.js.map