"""Deck assembly module for battle cards.

Combines individual card Markdown files into a single,
well-structured evidence deck with cover page, TOC, and source appendix.
"""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

from src.battlecards.card_templates import BattleCard, FIASection, render_card


# ---------------------------------------------------------------------------
# Card metadata for TOC generation
# ---------------------------------------------------------------------------

_CARD_METADATA = [
    {
        "number": 1,
        "filename": "card_01_market_valuation.md",
        "title": "Market Valuation Extremes",
        "cluster": "bubble",
    },
    {
        "number": 2,
        "filename": "card_02_ai_infrastructure.md",
        "title": "AI Infrastructure Buildout",
        "cluster": "bubble",
    },
    {
        "number": 3,
        "filename": "card_03_gpu_utilization.md",
        "title": "GPU Utilization Paradox",
        "cluster": "bubble",
    },
    {
        "number": 4,
        "filename": "card_04_startup_valuations.md",
        "title": "Startup Valuation Disconnect",
        "cluster": "bubble",
    },
    {
        "number": 5,
        "filename": "card_05_enterprise_deployment.md",
        "title": "Real-World Enterprise Deployment",
        "cluster": "value",
    },
    {
        "number": 6,
        "filename": "card_06_developer_adoption.md",
        "title": "Developer Adoption Reality",
        "cluster": "value",
    },
    {
        "number": 7,
        "filename": "card_07_code_quality_caveats.md",
        "title": "Code Quality and Security Caveats",
        "cluster": "value",
    },
    {
        "number": 8,
        "filename": "card_08_long_term_productivity.md",
        "title": "Long-Term Productivity Trajectory",
        "cluster": "value",
    },
]


class DeckGenerator:
    """Assemble individual battle cards into a complete evidence deck.

    Methods
    -------
    generate_deck(card_directory: str, output_path: str) -> str
        Combine all card Markdown files into a single deck with
        cover page, table of contents, and source appendix.
    """

    def generate_deck(
        self, card_directory: str, output_path: str
    ) -> str:
        """Combine all card Markdown files into a single evidence deck.

        Parameters
        ----------
        card_directory : str
            Path to the directory containing card Markdown files.
        output_path : str
            Destination path for the assembled deck Markdown file.

        Returns
        -------
        str
            Absolute path to the generated deck file.
        """
        card_dir = Path(card_directory)
        output_file = Path(output_path)
        output_file.parent.mkdir(parents=True, exist_ok=True)

        # Collect all sources
        all_sources: set[str] = set()

        lines: list[str] = []

        # ---- Cover page ----
        lines.append("# AI Bubble Battle Cards — Evidence Deck")
        lines.append("")
        lines.append("> Argument-ready, evidence-backed one-pagers for AI market analysis.")
        now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
        lines.append(f"> Last updated: {now_str}")
        lines.append("")

        # ---- Table of Contents ----
        lines.append("## Table of Contents")
        lines.append("")
        lines.append("### Cluster A: The Bubble Exists")
        lines.append("")
        for meta in _CARD_METADATA[:4]:
            lines.append(
                f"- [{meta['title']}](cards/{meta['filename']})"
            )
        lines.append("")
        lines.append("### Cluster B: LLMs Are Still Valuable")
        lines.append("")
        for meta in _CARD_METADATA[4:]:
            lines.append(
                f"- [{meta['title']}](cards/{meta['filename']})"
            )
        lines.append("")
        lines.append("---")
        lines.append("")

        # ---- Full card content ----
        for meta in _CARD_METADATA:
            card_file = card_dir / meta["filename"]
            if card_file.exists():
                card_content = card_file.read_text(encoding="utf-8")
                lines.append(card_content)
                lines.append("")
                lines.append("---")
                lines.append("")
            else:
                lines.append(f"*Card {meta['number']} ({meta['title']}) not found.*")
                lines.append("")

        # ---- Source Appendix ----
        lines.append("## Source Appendix")
        lines.append("")
        lines.append("*Primary data sources referenced across all battle cards:*")
        lines.append("")

        # If we have collected sources, list them; otherwise provide defaults
        if all_sources:
            for source in sorted(all_sources):
                lines.append(f"- {source}")
        else:
            lines.append("- Yale/Shiller CAPE data (multpl.com)")
            lines.append("- FRED economic indicators")
            lines.append("- World Bank debt & GDP datasets")
            lines.append("- Industry research reports (2024–2026)")

        lines.append("")

        deck_content = "\n".join(lines)
        output_file.write_text(deck_content, encoding="utf-8")

        return str(output_file.resolve())

    def generate_deck_from_cards(
        self, cards: list[BattleCard], output_path: str
    ) -> str:
        """Generate a deck directly from BattleCard instances.

        Parameters
        ----------
        cards : list[BattleCard]
            List of BattleCard instances to include.
        output_path : str
            Destination path for the deck file.

        Returns
        -------
        str
            Absolute path to the generated deck file.
        """
        output_file = Path(output_path)
        output_file.parent.mkdir(parents=True, exist_ok=True)

        all_sources: set[str] = set()
        for card in cards:
            all_sources.update(card.sources)

        lines: list[str] = []

        # Cover page
        lines.append("# AI Bubble Battle Cards — Evidence Deck")
        lines.append("")
        lines.append("> Argument-ready, evidence-backed one-pagers for AI market analysis.")
        now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
        lines.append(f"> Last updated: {now_str}")
        lines.append("")

        # TOC
        lines.append("## Table of Contents")
        lines.append("")

        bubble_cards = [c for c in cards if c.cluster == "bubble"]
        value_cards = [c for c in cards if c.cluster == "value"]

        if bubble_cards:
            lines.append("### Cluster A: The Bubble Exists")
            lines.append("")
            for card in sorted(bubble_cards, key=lambda c: c.card_number):
                safe_title = card.title.lower().replace(" ", "_")
                lines.append(f"- [Card {card.card_number}: {card.title}]")
            lines.append("")

        if value_cards:
            lines.append("### Cluster B: LLMs Are Still Valuable")
            lines.append("")
            for card in sorted(value_cards, key=lambda c: c.card_number):
                lines.append(f"- [Card {card.card_number}: {card.title}]")
            lines.append("")

        lines.append("---")
        lines.append("")

        # Card content
        for card in sorted(cards, key=lambda c: c.card_number):
            rendered = render_card(card)
            lines.append(rendered)
            lines.append("")
            lines.append("---")
            lines.append("")

        # Source appendix
        lines.append("## Source Appendix")
        lines.append("")
        for source in sorted(all_sources):
            lines.append(f"- {source}")
        lines.append("")

        deck_content = "\n".join(lines)
        output_file.write_text(deck_content, encoding="utf-8")

        return str(output_file.resolve())
