import uuid
from datetime import datetime

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

from app.api.deps import get_current_user
from app.database import get_db
from app.models.user import User
from app.models.brand import Brand
from app.schemas.citation import (
    CitationListResponse,
    CitationStatsResponse,
)
from app.services.citation import (
    get_citation_stats,
    get_citations,
)

router = APIRouter()


@router.get("/", response_model=CitationListResponse)
async def list_citations(
    query_id: uuid.UUID | None = Query(None),
    platform: str | None = Query(None),
    start_date: datetime | None = Query(None),
    end_date: datetime | None = Query(None),
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items, total = await get_citations(
        db,
        current_user.id,
        query_id=query_id,
        platform=platform,
        start_date=start_date,
        end_date=end_date,
        skip=skip,
        limit=limit,
    )
    return {"items": items, "total": total}


@router.get("/stats", response_model=CitationStatsResponse)
async def citation_stats(
    brand_id: uuid.UUID | None = Query(None),
    query_id: uuid.UUID | None = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    # If brand_id is provided, verify the brand exists and belongs to user
    if brand_id is not None:
        brand_stmt = select(Brand).where(
            Brand.id == brand_id,
            Brand.user_id == current_user.id,
        )
        brand_result = await db.execute(brand_stmt)
        brand = brand_result.scalar_one_or_none()

        if brand is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="品牌不存在",
            )

    stats = await get_citation_stats(
        db, current_user.id, query_id=query_id, brand_id=brand_id
    )
    return stats

