"""{{ wizard_class }} - Generated by Pattern-Compose

Domain: {{ domain}}
Patterns: {{ ', '.join(pattern_ids) }}
Generated: Auto-generated by Empathy Framework
"""

from datetime import datetime
from typing import Any
from uuid import uuid4

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel


router = APIRouter(
    prefix="/wizards/{{ wizard_name }}",
    tags=["wizards"],
)


# Request/Response Models
class WizardRequest(BaseModel):
    """Request model for wizard."""
    input: str
    context: dict[str, Any] | None = None


class WizardResponse(BaseModel):
    """Response model for wizard."""
    success: bool
    output: str
    wizard_id: str | None = None
    error: str | None = None


# Session storage (Redis in production, memory for development)
_wizard_sessions: dict[str, dict[str, Any]] = {}


@router.post("/start")
async def start_wizard():
    """Start {{ wizard_name }} wizard session.

    Returns wizard_id and first step configuration.
    """
    wizard_id = str(uuid4())

    session_data = {
        "wizard_id": wizard_id,
        "wizard_type": "{{ wizard_name }}",
        "current_step": 1,
        "total_steps": 5,  # TODO: Adjust based on your wizard
        "collected_data": {},
        "created_at": datetime.now().isoformat(),
    }

    _wizard_sessions[wizard_id] = session_data

    return {
        "wizard_id": wizard_id,
        "current_step": 1,
        "total_steps": 5,
        "message": "Wizard started successfully",
    }


@router.post("/{wizard_id}/step")
async def submit_step(wizard_id: str, step_data: dict[str, Any]):
    """Submit data for current step.

    Validates step sequence and stores data.
    """
    if wizard_id not in _wizard_sessions:
        raise HTTPException(404, "Wizard session not found")

    session = _wizard_sessions[wizard_id]
    current_step = session["current_step"]
    total_steps = session["total_steps"]

    # Validate step number
    submitted_step = step_data.get("step", current_step)
    if submitted_step != current_step:
        raise HTTPException(
            422,
            f"Expected step {current_step}, got step {submitted_step}"
        )

    # Store data
    session["collected_data"].update(step_data.get("data", {}))
    session["updated_at"] = datetime.now().isoformat()

    # Advance to next step
    if current_step < total_steps:
        session["current_step"] = current_step + 1

    return {
        "wizard_id": wizard_id,
        "current_step": session["current_step"],
        "total_steps": total_steps,
        "message": f"Step {current_step} completed",
    }


{% if has_approval %}
@router.post("/{wizard_id}/preview")
async def preview_report(wizard_id: str):
    """Generate preview without finalizing.

    Allows user to review before explicit approval.
    """
    if wizard_id not in _wizard_sessions:
        raise HTTPException(404, "Wizard session not found")

    session = _wizard_sessions[wizard_id]

    if session["current_step"] != session["total_steps"]:
        raise HTTPException(400, "Complete all steps before preview")

    # Generate preview
    preview = _generate_report(session["collected_data"])
    session["preview_report"] = preview
    session["preview_generated_at"] = datetime.now().isoformat()

    return {
        "preview": preview,
        "message": "Preview generated. Review and approve to finalize.",
    }


@router.post("/{wizard_id}/save")
async def save_report(wizard_id: str, approval: dict[str, Any]):
    """Finalize report with user approval.

    Requires preview generated and explicit user approval.
    """
    if wizard_id not in _wizard_sessions:
        raise HTTPException(404, "Wizard session not found")

    session = _wizard_sessions[wizard_id]

    # Verify preview generated
    if "preview_report" not in session:
        raise HTTPException(
            400,
            "Must generate preview before saving. Call /preview first."
        )

    # Verify user approval
    if not approval.get("user_approved", False):
        raise HTTPException(
            400,
            "User approval required. Set 'user_approved': true"
        )

    # Mark as complete
    session["completed"] = True
    session["completed_at"] = datetime.now().isoformat()
    session["final_report"] = session["preview_report"]

    return {
        "wizard_id": wizard_id,
        "completed": True,
        "report": session["final_report"],
        "message": "Report finalized successfully",
    }
{% endif %}


@router.get("/{wizard_id}/report")
async def get_report(wizard_id: str):
    """Retrieve completed report.

    Only available after wizard is completed.
    """
    if wizard_id not in _wizard_sessions:
        raise HTTPException(404, "Wizard session not found")

    session = _wizard_sessions[wizard_id]

    if not session.get("completed", False):
        raise HTTPException(422, "Wizard not yet completed")

    return {
        "wizard_id": wizard_id,
        "report": _generate_report(session["collected_data"]),
    }


def _generate_report(collected_data: dict[str, Any]) -> dict[str, Any]:
    """Generate report from collected data.

    TODO: Customize report generation for your wizard.
    """
    return {
        "data": collected_data,
        "generated_at": datetime.now().isoformat(),
        "wizard_type": "{{ wizard_name }}",
    }


# Export router
__all__ = ["router"]
