"""Analytics REST API routes.

Provides endpoints for recording and querying analytics data.

⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
"""

from __future__ import annotations

from datetime import datetime

from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession

from {{ project_name }}.analytics.service import get_events, record_event
{% if dashboard_enabled %}
from {{ project_name }}.analytics.service import get_summary
{% endif %}
from {{ project_name }}.database import get_db
from {{ project_name }}.schemas.analytics import (
    EventCreate,
    EventResponse,
    EventsListResponse,
{% if track_page_views %}
    PageViewCreate,
{% endif %}
{% if dashboard_enabled %}
    AnalyticsSummary,
{% endif %}
)

router = APIRouter(prefix="/analytics", tags=["analytics"])


@router.post("/events", response_model=EventResponse, status_code=201)
async def create_event(
    event_data: EventCreate,
    db: AsyncSession = Depends(get_db),
) -> EventResponse:
    """Record a new analytics event."""
    await record_event(
        event_name=event_data.event_name,
        category=event_data.category,
        properties=event_data.properties,
        session_id=event_data.session_id,
        page_url=event_data.page_url,
        db=db,
    )
    await db.commit()

    # Return the created event (simplified)
    return EventResponse(
        id=0,
        event_name=event_data.event_name,
        category=event_data.category,
        properties=event_data.properties,
        session_id=event_data.session_id,
        page_url=event_data.page_url,
        timestamp=datetime.utcnow(),
    )

{% if track_page_views %}


@router.post("/page-views", status_code=201)
async def record_page_view(
    page_view: PageViewCreate,
    db: AsyncSession = Depends(get_db),
) -> dict[str, str]:
    """Record a page view event."""
    properties: dict = {"page_title": page_view.page_title}
{% if track_referrer %}
    if page_view.referrer:
        properties["referrer"] = page_view.referrer
{% endif %}

    await record_event(
        event_name="page_view",
        category="navigation",
        properties=properties,
        session_id=page_view.session_id,
        page_url=page_view.page_url,
        db=db,
    )
    await db.commit()
    return {"status": "ok"}
{% endif %}


@router.get("/events", response_model=EventsListResponse)
async def list_events(
    event_name: str | None = Query(default=None, description="Filter by event name"),
    category: str | None = Query(default=None, description="Filter by category"),
    start_date: datetime | None = Query(default=None, description="Start date filter"),
    end_date: datetime | None = Query(default=None, description="End date filter"),
    page: int = Query(default=1, ge=1, description="Page number"),
    page_size: int = Query(default=50, ge=1, le=200, description="Items per page"),
    db: AsyncSession = Depends(get_db),
) -> EventsListResponse:
    """List analytics events with filtering."""
    events, total = await get_events(
        db,
        event_name=event_name,
        category=category,
        start_date=start_date,
        end_date=end_date,
        page=page,
        page_size=page_size,
    )
    return EventsListResponse(
        items=[EventResponse.model_validate(e) for e in events],
        total=total,
        page=page,
        page_size=page_size,
    )

{% if dashboard_enabled %}


@router.get("/summary", response_model=AnalyticsSummary)
async def get_analytics_summary(
    days: int = Query(default={{ retention_days }}, ge=1, le=365, description="Number of days"),
    db: AsyncSession = Depends(get_db),
) -> AnalyticsSummary:
    """Get analytics summary for the dashboard."""
    summary = await get_summary(db, days=days)
    return AnalyticsSummary(**summary)
{% endif %}
