#!/usr/bin/env python3
"""Assemble perspectives HTML from scaffold + 26 enriched lens files.

Version is controlled by PERSPECTIVES_VERSION env var (defaults to 3).
Each version reads its matching scaffold and writes its matching output.
"""
import re
import json
import os
from datetime import datetime
from pathlib import Path

VERSION = int(os.environ.get("PERSPECTIVES_VERSION", "3"))

BUILD = Path(__file__).parent
DOCS = BUILD.parent
SCAFFOLD = DOCS / f"perspectives-vlm-primary-hybrid-nav-v{VERSION}-scaffold.html"
OUTPUT = DOCS / f"perspectives-vlm-primary-hybrid-nav-v{VERSION}.html"
SECTIONS_JSON = DOCS / f"perspectives-vlm-primary-hybrid-nav-v{VERSION}-sections.json"

LENS_NAMES = {
    "01": "First Principles X-Ray", "02": "Abstraction Elevator",
    "03": "Dependency Telescope", "04": "Sensitivity Surface",
    "05": "Evolution Timeline", "06": "Second-Order Effects",
    "07": "Landscape Map", "08": "Analogy Bridge",
    "09": "Tradeoff Radar", "10": "Failure Pre-mortem",
    "11": "Red Team Brief", "12": "Anti-Pattern Gallery",
    "13": "Constraint Analysis", "14": "The Inversion",
    "15": "Constraint Relaxation", "16": "Composition Lab",
    "17": "Transfer Matrix", "18": "Decision Tree",
    "19": "Scale Microscope", "20": "Day-in-the-Life",
    "21": "Stakeholder Kaleidoscope", "22": "Learning Staircase",
    "23": "Energy Landscape", "24": "Gap Finder",
    "25": "Blind Spot Scan", "26": "Question Horizon",
}

CATEGORIES = {
    "01": "decompose", "02": "decompose", "03": "decompose", "04": "decompose",
    "05": "evolve", "06": "evolve",
    "07": "position", "08": "position", "09": "position",
    "10": "stress", "11": "stress", "12": "stress", "13": "stress",
    "14": "generate", "15": "generate", "16": "generate", "17": "generate",
    "18": "apply", "19": "apply", "20": "apply",
    "21": "human", "22": "human", "23": "human",
    "24": "discover", "25": "discover", "26": "discover",
}


def main():
    scaffold = SCAFFOLD.read_text()
    replaced = 0

    for nn in sorted(LENS_NAMES.keys()):
        lens_file = BUILD / f"lens-{nn}.html"
        if not lens_file.exists():
            print(f"  SKIP lens-{nn}: file not found")
            continue

        lens_html = lens_file.read_text().strip()
        # Pattern: <section class="lens" id="lens-NN">...</section>
        pattern = rf'<section class="lens" id="lens-{nn}">.*?</section>'
        match = re.search(pattern, scaffold, re.DOTALL)
        if match:
            scaffold = scaffold[:match.start()] + lens_html + scaffold[match.end():]
            replaced += 1
            print(f"  OK  lens-{nn}: {len(lens_html):,} chars")
        else:
            print(f"  ERR lens-{nn}: section not found in scaffold")

    print(f"\nReplaced {replaced}/26 sections")

    # Update timestamp in hero
    now = datetime.now()
    scaffold = re.sub(
        r'Session \d+ ·.*?· Version 2',
        f'Session 98 · <span>{now.strftime("%B %d, %Y %H:%M")} IST</span> · Version 2',
        scaffold
    )

    # Write final HTML
    OUTPUT.write_text(scaffold)
    print(f"Written: {OUTPUT} ({len(scaffold):,} chars)")

    # Build sections.json from TTS files
    sections = []
    for nn in sorted(LENS_NAMES.keys()):
        tts_file = BUILD / f"lens-{nn}-tts.txt"
        text = tts_file.read_text().strip() if tts_file.exists() else ""
        crosslens_file = BUILD / f"lens-{nn}-crosslens.txt"
        crosslens = crosslens_file.read_text().strip() if crosslens_file.exists() else ""

        # Extract key findings from crosslens (first 3 lines)
        findings = [l.strip("- •").strip() for l in crosslens.split("\n")[:3] if l.strip()]

        sections.append({
            "id": f"lens-{nn}",
            "title": LENS_NAMES[nn],
            "category": CATEGORIES[nn],
            "text": text,
            "findings": findings,
        })

    sections_data = {
        "title": "Research Perspectives: VLM Primary Hybrid Nav",
        "source": "docs/RESEARCH-VLM-PRIMARY-HYBRID-NAV.md",
        "source_hash": "f26269eb",
        "version": 2,
        "generated_at": now.isoformat(),
        "previous_version": "perspectives-vlm-primary-hybrid-nav-v1-sections.json",
        "sections": sections,
    }

    SECTIONS_JSON.write_text(json.dumps(sections_data, indent=2, ensure_ascii=False))
    print(f"Written: {SECTIONS_JSON}")


if __name__ == "__main__":
    main()
