"""{{ wizard_name | title | replace('_', ' ') }} Domain Wizard.

Auto-generated by Empathy Framework Scaffolding
Methodology: {{ methodology }}
Domain: {{ domain }}
Patterns: {{ pattern_ids | join(', ') }}
Empathy Level: {{ empathy_level | default(2) }}
Generated: {{ timestamp }}
"""

import logging
from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from empathy_llm_toolkit.memory_manager import MemoryManager
from empathy_llm_toolkit.wizards.base_wizard import WizardConfig

logger = logging.getLogger(__name__)

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


# Wizard Configuration
WIZARD_CONFIG = WizardConfig(
    wizard_id="{{ wizard_name }}",
    name="{{ wizard_name | title | replace('_', ' ') }}",
    description="{{ description | default('Domain wizard for ' + domain) }}",
    domain="{{ domain }}",
    empathy_level={{ empathy_level | default(2) }},
    {% if 'educational_banner' in pattern_ids %}
    show_educational_banner=True,
    {% endif %}
)


# Request/Response Models
{% if 'linear_flow' in pattern_ids %}
class StartRequest(BaseModel):
    """Request to start wizard."""
    context: dict[str, Any] = Field(default_factory=dict, description="Initial context")


class StartResponse(BaseModel):
    """Response from starting wizard."""
    wizard_id: str
    current_step: int
    total_steps: int
    {% if 'educational_banner' in pattern_ids %}
    educational_banner: dict[str, Any] | None = None
    {% endif %}


class StepSubmission(BaseModel):
    """Step data submission."""
    step: int
    data: dict[str, Any]


class StepResult(BaseModel):
    """Step submission result."""
    wizard_id: str
    current_step: int
    total_steps: int
    completed: bool = False
    {% if 'user_guidance' in pattern_ids %}
    next_step_guidance: str | None = None
    {% endif %}
{% endif %}


{% if 'approval' in pattern_ids %}
class PreviewRequest(BaseModel):
    """Request to generate preview."""
    pass


class PreviewResult(BaseModel):
    """Preview generation result."""
    wizard_id: str
    preview_report: dict[str, Any]
    {% if 'user_guidance' in pattern_ids %}
    approval_guidance: str
    {% endif %}


class SaveRequest(BaseModel):
    """Request to save with approval."""
    approval: dict[str, Any] = Field(..., description="User approval data")


class SaveResult(BaseModel):
    """Save result."""
    wizard_id: str
    completed: bool
    final_report: dict[str, Any]
{% endif %}


# In-memory session storage (replace with Redis in production)
sessions: dict[str, dict[str, Any]] = {}


{% if 'linear_flow' in pattern_ids %}
@router.post("/start", response_model=StartResponse)
async def start_wizard(request: StartRequest) -> StartResponse:
    """Start a new wizard session.

    Args:
        request: Start request with initial context

    Returns:
        Wizard session info

    Raises:
        HTTPException: If initialization fails
    """
    try:
        wizard_id = f"{{ wizard_name }}_{len(sessions) + 1}"

        # Initialize session
        session = {
            "wizard_id": wizard_id,
            "current_step": 1,
            "total_steps": {{ total_steps | default(5) }},
            "context": request.context,
            "step_data": {},
            "completed": False,
        }

        sessions[wizard_id] = session

        response = StartResponse(
            wizard_id=wizard_id,
            current_step=1,
            total_steps={{ total_steps | default(5) }},
        )

        {% if 'educational_banner' in pattern_ids %}
        # Add educational banner for Level {{ empathy_level | default(2) }}
        response.educational_banner = {
            "message": "{{ educational_message | default('This wizard will guide you through the process step by step.') }}",
            "level": {{ empathy_level | default(2) }},
        }
        {% endif %}

        logger.info(f"Started wizard session: {wizard_id}")
        return response

    except Exception as e:
        logger.exception(f"Failed to start wizard: {e}")
        raise HTTPException(status_code=500, detail=f"Wizard start failed: {str(e)}")


@router.post("/{wizard_id}/step", response_model=StepResult)
async def submit_step(wizard_id: str, submission: StepSubmission) -> StepResult:
    """Submit data for a wizard step.

    Args:
        wizard_id: Wizard session ID
        submission: Step data submission

    Returns:
        Step result with next step info

    Raises:
        HTTPException: If session not found or validation fails
    """
    # Validate session
    if wizard_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")

    session = sessions[wizard_id]

    {% if 'step_validation' in pattern_ids %}
    # Validate step sequence
    if submission.step != session["current_step"]:
        raise HTTPException(
            status_code=400,
            detail=f"Expected step {session['current_step']}, got {submission.step}"
        )
    {% endif %}

    try:
        # Store step data
        session["step_data"][submission.step] = submission.data

        # Move to next step
        session["current_step"] = submission.step + 1

        # Check if completed
        completed = session["current_step"] > session["total_steps"]
        session["completed"] = completed

        result = StepResult(
            wizard_id=wizard_id,
            current_step=session["current_step"],
            total_steps=session["total_steps"],
            completed=completed,
        )

        {% if 'user_guidance' in pattern_ids %}
        # Provide guidance for next step (Level {{ empathy_level | default(2) }} Empathy)
        if not completed:
            result.next_step_guidance = await _get_step_guidance(
                session["current_step"],
                session["step_data"]
            )
        {% endif %}

        logger.info(f"Step {submission.step} submitted for {wizard_id}")
        return result

    except Exception as e:
        logger.exception(f"Step submission failed: {e}")
        raise HTTPException(status_code=500, detail=f"Step submission failed: {str(e)}")
{% endif %}


{% if 'approval' in pattern_ids %}
@router.post("/{wizard_id}/preview", response_model=PreviewResult)
async def generate_preview(wizard_id: str, request: PreviewRequest) -> PreviewResult:
    """Generate preview for user review.

    Args:
        wizard_id: Wizard session ID
        request: Preview request

    Returns:
        Preview report for user review

    Raises:
        HTTPException: If session not found or not ready for preview
    """
    if wizard_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")

    session = sessions[wizard_id]

    # Validate all steps completed
    if not session.get("completed"):
        raise HTTPException(status_code=400, detail="All steps must be completed before preview")

    try:
        # Generate preview
        preview_report = await _generate_preview_report(session["step_data"])

        # Store preview in session
        session["preview_report"] = preview_report

        result = PreviewResult(
            wizard_id=wizard_id,
            preview_report=preview_report,
        )

        {% if 'user_guidance' in pattern_ids %}
        # Provide approval guidance (Level {{ empathy_level | default(2) }} Empathy)
        result.approval_guidance = (
            "Please review the preview carefully. "
            "You can edit any information before final approval."
        )
        {% endif %}

        logger.info(f"Preview generated for {wizard_id}")
        return result

    except Exception as e:
        logger.exception(f"Preview generation failed: {e}")
        raise HTTPException(status_code=500, detail=f"Preview generation failed: {str(e)}")


@router.post("/{wizard_id}/save", response_model=SaveResult)
async def save_with_approval(wizard_id: str, request: SaveRequest) -> SaveResult:
    """Save wizard data with user approval.

    Args:
        wizard_id: Wizard session ID
        request: Save request with approval

    Returns:
        Final save result

    Raises:
        HTTPException: If session not found or approval missing
    """
    if wizard_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")

    session = sessions[wizard_id]

    # Validate preview was generated
    if "preview_report" not in session:
        raise HTTPException(status_code=400, detail="Preview must be generated before saving")

    # Validate approval
    if not request.approval.get("user_approved"):
        raise HTTPException(status_code=400, detail="User approval required")

    try:
        # Generate final report
        final_report = await _generate_final_report(
            session["step_data"],
            session["preview_report"]
        )

        # Mark as finalized
        session["final_report"] = final_report
        session["finalized"] = True

        logger.info(f"Wizard {wizard_id} saved with approval")

        return SaveResult(
            wizard_id=wizard_id,
            completed=True,
            final_report=final_report,
        )

    except Exception as e:
        logger.exception(f"Save failed: {e}")
        raise HTTPException(status_code=500, detail=f"Save failed: {str(e)}")
{% endif %}


@router.get("/{wizard_id}/report", response_model=dict[str, Any])
async def get_report(wizard_id: str) -> dict[str, Any]:
    """Get wizard report.

    Args:
        wizard_id: Wizard session ID

    Returns:
        Complete wizard report

    Raises:
        HTTPException: If session not found
    """
    if wizard_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")

    session = sessions[wizard_id]

    return {
        "wizard_id": wizard_id,
        "step_data": session.get("step_data", {}),
        {% if 'approval' in pattern_ids %}
        "preview_report": session.get("preview_report"),
        "final_report": session.get("final_report"),
        "finalized": session.get("finalized", False),
        {% endif %}
    }


# Helper functions
{% if 'user_guidance' in pattern_ids %}
async def _get_step_guidance(step: int, step_data: dict[int, Any]) -> str:
    """Get guidance for next step (Level {{ empathy_level | default(2) }} Empathy).

    Args:
        step: Current step number
        step_data: Previous step data

    Returns:
        Guidance message
    """
    # TODO: Implement actual guidance generation
    return f"Please complete step {step} with the required information."
{% endif %}


{% if 'approval' in pattern_ids %}
async def _generate_preview_report(step_data: dict[int, Any]) -> dict[str, Any]:
    """Generate preview report.

    Args:
        step_data: All collected step data

    Returns:
        Preview report
    """
    # TODO: Implement actual preview generation
    return {
        "summary": "Preview of collected data",
        "data": step_data,
    }


async def _generate_final_report(
    step_data: dict[int, Any],
    preview_report: dict[str, Any]
) -> dict[str, Any]:
    """Generate final report after approval.

    Args:
        step_data: All collected step data
        preview_report: Previously generated preview

    Returns:
        Final report
    """
    # TODO: Implement actual final report generation
    return {
        "summary": "Final report",
        "data": step_data,
        "preview": preview_report,
        "finalized_at": "2025-01-05T00:00:00Z",
    }
{% endif %}
