"""Tests for deck archetype definitions — validates structure and generation."""

from __future__ import annotations

from pathlib import Path

import pytest

from pptx_mcp.agents.archetypes import ARCHETYPES, DeckArchetype
from pptx_mcp.agents.planner import PlannerInput, SlidePlannerAgent
from pptx_mcp.brand.defaults import get_preset
from pptx_mcp.engine.generator import DeckGenerator
from pptx_mcp.models.slides import SlideType


# --- Structural validation ---


class TestArchetypeDefinitions:
    def test_all_archetypes_load(self) -> None:
        assert len(ARCHETYPES) == 27
        for name, arch in ARCHETYPES.items():
            assert isinstance(arch, DeckArchetype)
            assert arch.name == name

    def test_archetypes_have_valid_slide_types(self) -> None:
        valid_types = set(SlideType)
        for name, arch in ARCHETYPES.items():
            for slot in arch.slots:
                assert isinstance(slot.slide_type, SlideType), (
                    f"Archetype '{name}' has invalid slide_type in slot: {slot}"
                )
                assert slot.slide_type in valid_types

    def test_each_archetype_starts_with_title(self) -> None:
        for name, arch in ARCHETYPES.items():
            assert arch.slots[0].slide_type == SlideType.TITLE, (
                f"Archetype '{name}' should start with TITLE"
            )

    def test_archetype_slot_counts(self) -> None:
        for name, arch in ARCHETYPES.items():
            assert len(arch.slots) >= 3, f"Archetype '{name}' has too few slots"
            assert arch.min_slides >= 3
            assert arch.max_slides >= arch.min_slides

    def test_archetype_display_names_nonempty(self) -> None:
        for name, arch in ARCHETYPES.items():
            assert arch.display_name.strip(), f"{name}: empty display_name"

    def test_archetype_descriptions_nonempty(self) -> None:
        for name, arch in ARCHETYPES.items():
            assert arch.description.strip(), f"{name}: empty description"


# --- Category lists ---

ORIGINAL_ARCHETYPES = [
    "pitch_deck", "board_deck", "sales_deck", "all_hands",
    "project_update", "training", "strategy_deck", "due_diligence",
    "market_analysis", "org_design", "competitive_assessment",
    "transformation_roadmap",
]

NEW_ARCHETYPES = [
    "assessment", "opportunity_assessment", "strategy_training",
    "template_guide", "executive_overview", "analysis_deck",
    "cost_breakdown", "architecture_review", "analytics_dashboard",
    "product_launch", "case_study", "quarterly_earnings",
    "onboarding", "annual_report", "conference_talk",
]


def test_original_archetypes_present():
    """Original 12 archetypes should still be registered."""
    for name in ORIGINAL_ARCHETYPES:
        assert name in ARCHETYPES, f"Original archetype {name!r} missing"


def test_new_archetypes_present():
    """All 15 new v0.5.0 archetypes should be registered."""
    for name in NEW_ARCHETYPES:
        assert name in ARCHETYPES, f"New archetype {name!r} missing"


# --- Plan + generate tests for new archetypes ---


@pytest.mark.parametrize("archetype_name", NEW_ARCHETYPES)
def test_new_archetypes_generate(archetype_name: str, tmp_path: Path):
    """Each new archetype should plan and generate without errors."""
    planner = SlidePlannerAgent()
    plan_input = PlannerInput(
        topic=f"Test {archetype_name}",
        audience="executive",
        num_slides=8,
        key_points=["Point A", "Point B", "Point C"],
        deck_type=archetype_name,
        company="TestCo",
    )
    definition = planner.run(plan_input)
    assert len(definition.slides) >= 3

    brand = get_preset("consulting")
    generator = DeckGenerator(brand=brand)
    out = tmp_path / f"{archetype_name}.pptx"
    result = generator.generate(definition, str(out))
    assert Path(result).exists()


# --- Scale tests ---


def test_archetype_scale_up(tmp_path: Path):
    """When target slides > slot count, planner should add filler slides."""
    planner = SlidePlannerAgent()
    plan_input = PlannerInput(
        topic="Scale Up Test",
        audience="executive",
        num_slides=20,
        key_points=["KP1", "KP2", "KP3"],
        deck_type="executive_overview",  # 8 slots, requesting 20
    )
    definition = planner.run(plan_input)
    assert len(definition.slides) > len(ARCHETYPES["executive_overview"].slots)


def test_archetype_scale_down(tmp_path: Path):
    """When target slides < slot count, planner should trim to fit."""
    planner = SlidePlannerAgent()
    plan_input = PlannerInput(
        topic="Scale Down Test",
        audience="executive",
        num_slides=5,
        key_points=["KP1"],
        deck_type="architecture_review",  # 11 slots, requesting 5
    )
    definition = planner.run(plan_input)
    assert len(definition.slides) <= len(ARCHETYPES["architecture_review"].slots)
