"""Campaign routes - /campaigns/* endpoints."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException, Query

router = APIRouter(tags=["campaigns"])


def _get_team() -> Any:
    """Get the team instance from app state."""
    return None


@router.get("/campaigns")
async def list_campaigns() -> dict[str, Any]:
    """List all campaigns."""
    team = _get_team()
    if team is None:
        raise HTTPException(status_code=404, detail="Campaigns not available")

    if not hasattr(team, "list_campaign_states"):
        raise HTTPException(status_code=404, detail="Campaigns not available")

    try:
        states = team.list_campaign_states()
        return {
            "items": [
                {
                    "campaign_id": state.campaign_id,
                    "total_events": state.total_events,
                    "completed_events": state.completed_events,
                    "failed_events": state.errored_events,
                    "pending_events": state.queued_events,
                }
                for state in states
            ]
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/campaigns/{campaign_id}")
async def get_campaign(campaign_id: str) -> dict[str, Any]:
    """Get campaign state."""
    team = _get_team()
    if team is None:
        raise HTTPException(status_code=404, detail="Campaigns not available")

    if not hasattr(team, "campaign_state"):
        raise HTTPException(status_code=404, detail="Campaigns not available")

    try:
        state = team.campaign_state(campaign_id)
        return {
            "campaign_id": state.campaign_id,
            "total_events": state.total_events,
            "completed_events": state.completed_events,
            "failed_events": state.errored_events,
            "pending_events": state.queued_events,
        }
    except ValueError:
        raise HTTPException(status_code=404, detail="Campaign not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/campaigns/{campaign_id}/events")
async def list_campaign_events(
    campaign_id: str,
    status: str | None = Query(None),
) -> dict[str, Any]:
    """List campaign events."""
    team = _get_team()
    if team is None:
        raise HTTPException(status_code=404, detail="Campaigns not available")

    if not hasattr(team, "list_campaign_events"):
        raise HTTPException(status_code=404, detail="Campaigns not available")

    try:
        events = team.list_campaign_events(campaign_id)

        if status:
            events = [e for e in events if e.status == status]

        return {
            "items": [
                {
                    "id": e.id,
                    "topic": e.topic,
                    "campaign_id": e.campaign_id,
                    "status": e.status,
                    "created_at": str(e.created_at),
                }
                for e in events
            ]
        }
    except ValueError:
        raise HTTPException(status_code=404, detail="Campaign not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


def create_campaign_routes(get_team) -> APIRouter:
    """Create campaign routes with team accessor."""
    global _get_team
    _get_team = get_team
    return router


__all__ = ["router", "create_campaign_routes"]
