#!/usr/bin/env python3
"""Example: end-to-end test invocation of the PPTX MCP pipeline.

Demonstrates:
  1. Planning a deck with the SlidePlanner agent
  2. Optimizing layout with the DesignAgent
  3. Generating the PPTX
  4. Reviewing the result
  5. Iterating improvements
  6. Re-generating the improved version
"""

from __future__ import annotations

import json
from pathlib import Path

from pptx_mcp.agents.designer import DesignAgent, DesignerInput
from pptx_mcp.agents.iterator import IterationAgent, IterationInput
from pptx_mcp.agents.planner import PlannerInput, SlidePlannerAgent
from pptx_mcp.agents.reviewer import ReviewAgent, ReviewerInput
from pptx_mcp.brand.config import resolve_brand_config
from pptx_mcp.engine.generator import DeckGenerator
from pptx_mcp.engine.parser import parse_presentation
from pptx_mcp.models.slides import PresentationDefinition
from pptx_mcp.review.engine import ReviewEngine

OUTPUT_DIR = Path("output")


def main() -> None:
    OUTPUT_DIR.mkdir(exist_ok=True)
    brand = resolve_brand_config(preset="executive")

    # --- Step 1: Plan ---
    print("=" * 60)
    print("Step 1: Planning presentation")
    print("=" * 60)

    planner = SlidePlannerAgent()
    plan = planner.run(PlannerInput(
        topic="AI-Driven Automation Strategy",
        audience="executive",
        num_slides=10,
        key_points=[
            "Market opportunity",
            "Current capabilities",
            "Proposed investment",
            "Expected ROI",
            "Risk factors",
        ],
        company="Acme Corp",
        author="Strategy Team",
    ))
    print(f"  Planned {len(plan.slides)} slides")
    for i, s in enumerate(plan.slides):
        print(f"    [{i}] {s.slide_type.value}: {s.title}")

    # --- Step 2: Design optimization ---
    print("\n" + "=" * 60)
    print("Step 2: Optimizing design")
    print("=" * 60)

    designer = DesignAgent()
    design_result = designer.run(DesignerInput(definition=plan, brand_preset="executive"))
    print(f"  Changes: {len(design_result.changes_made)}")
    for change in design_result.changes_made:
        print(f"    - {change}")

    # --- Step 3: Generate PPTX ---
    print("\n" + "=" * 60)
    print("Step 3: Generating PPTX")
    print("=" * 60)

    generator = DeckGenerator(brand=brand)
    output_path = generator.generate(design_result.definition, OUTPUT_DIR / "ai_strategy_v1.pptx")
    print(f"  Generated: {output_path}")

    # --- Step 4: Review ---
    print("\n" + "=" * 60)
    print("Step 4: Reviewing presentation")
    print("=" * 60)

    reviewer_agent = ReviewAgent()
    review_output = reviewer_agent.run(ReviewerInput(
        file_path=str(output_path),
        brand_preset="executive",
    ))
    review = review_output.review
    print(f"  Score: {review.overall_score}/10.0")
    print(f"  Issues: {review.total_issues}")
    print(f"  Summary: {review.summary}")

    # --- Step 5: Iterate ---
    print("\n" + "=" * 60)
    print("Step 5: Iterating improvements")
    print("=" * 60)

    if review_output.parsed_definition:
        iterator = IterationAgent()
        iter_result = iterator.run(IterationInput(
            definition=review_output.parsed_definition,
            review=review,
        ))
        print(f"  Fixes applied: {len(iter_result.fixes_applied)}")
        for fix in iter_result.fixes_applied:
            print(f"    - {fix}")
        print(f"  Remaining issues: {len(iter_result.remaining_issues)}")

        # --- Step 6: Re-generate ---
        print("\n" + "=" * 60)
        print("Step 6: Re-generating improved version")
        print("=" * 60)

        output_v2 = generator.generate(
            iter_result.definition, OUTPUT_DIR / "ai_strategy_v2.pptx"
        )
        print(f"  Generated: {output_v2}")

    # --- Also generate from the sample_deck.json ---
    print("\n" + "=" * 60)
    print("Bonus: Generating from sample_deck.json")
    print("=" * 60)

    sample_path = Path(__file__).parent / "sample_deck.json"
    if sample_path.exists():
        raw = sample_path.read_text(encoding="utf-8")
        sample_def = PresentationDefinition.model_validate(json.loads(raw))
        sample_brand = resolve_brand_config(
            path=str(Path(__file__).parent / "brand_config.yaml")
        )
        sample_gen = DeckGenerator(brand=sample_brand)
        sample_output = sample_gen.generate(sample_def, OUTPUT_DIR / "cloud_migration.pptx")
        print(f"  Generated: {sample_output}")

    print("\n" + "=" * 60)
    print("Done. Check the 'output/' directory for generated files.")
    print("=" * 60)


if __name__ == "__main__":
    main()
