"""Usage domain — HTTP routes."""
from __future__ import annotations

from datetime import date
from typing import Annotated, Optional
from uuid import UUID

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

from src.core.database import get_db
from src.core.dependencies import require_active_billing_for_project_id
from src.domain.auth.models import User
from src.domain.auth.router import get_current_user
from src.domain.cloud.dependencies import require_cloud_internal_token
from src.domain.usage.repository import (
    ProjectHostedAppUsageSnapshotRepository,
    WorkspaceUsageSnapshotRepository,
)
from src.domain.usage.schemas import (
    AIUsageAckResponse,
    AIUsageReportRequest,
    CurrentUsageResponse,
    ProjectHostedAppUsageHistoryResponse,
    WorkspaceUsageHistoryResponse,
)
from src.domain.usage.service import UsageService

project_router = APIRouter(
    prefix="/api/projects/{project_id}",
    tags=["usage"],
)
workspace_router = APIRouter(
    prefix="/api/workspaces/{workspace_id}",
    tags=["usage"],
)
cloud_router = APIRouter(
    prefix="/v1/cloud/usage",
    tags=["cloud-usage"],
    dependencies=[Depends(require_cloud_internal_token)],
)


def _get_service(db: AsyncSession = Depends(get_db)) -> UsageService:
    return UsageService(
        snapshot_repo=WorkspaceUsageSnapshotRepository(db),
        hosted_app_snapshot_repo=ProjectHostedAppUsageSnapshotRepository(db),
    )


# ---------------------------------------------------------------------------
# Project usage
# ---------------------------------------------------------------------------


@project_router.get("/usage/current", response_model=CurrentUsageResponse)
async def get_project_current_usage(
    project_id: UUID = Depends(require_active_billing_for_project_id),
    _: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    svc: UsageService = Depends(_get_service),
) -> CurrentUsageResponse:
    from src.domain.projects.repository import ProjectRepository
    from src.domain.billing.repository import WorkspaceSubscriptionRepository
    proj = await ProjectRepository(db).get_by_id(project_id)
    sub = await WorkspaceSubscriptionRepository(db).get_active(proj.workspace_id)
    period_start = sub.current_period_start.date() if sub else date.today().replace(day=1)
    period_end = sub.current_period_end.date() if sub else date.today()
    return await svc.get_current_usage(
        workspace_id=proj.workspace_id,
        billing_period_start=period_start,
        billing_period_end=period_end,
    )


@project_router.get("/usage/hosting/history", response_model=ProjectHostedAppUsageHistoryResponse)
async def get_project_hosting_usage_history(
    project_id: UUID = Depends(require_active_billing_for_project_id),
    _: User = Depends(get_current_user),
    from_date: Optional[date] = Query(None),
    to_date: Optional[date] = Query(None),
    svc: UsageService = Depends(_get_service),
) -> ProjectHostedAppUsageHistoryResponse:
    """Monitor-only generated-app requests and response bytes by day."""
    return await svc.get_project_hosted_app_usage_history(
        project_id, from_date=from_date, to_date=to_date
    )


# ---------------------------------------------------------------------------
# Workspace usage
# ---------------------------------------------------------------------------


@workspace_router.get("/usage/current", response_model=CurrentUsageResponse)
async def get_workspace_current_usage(
    workspace_id: UUID,
    _: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    svc: UsageService = Depends(_get_service),
) -> CurrentUsageResponse:
    from src.domain.billing.repository import WorkspaceSubscriptionRepository
    sub = await WorkspaceSubscriptionRepository(db).get_active(workspace_id)
    period_start = sub.current_period_start.date() if sub else date.today().replace(day=1)
    period_end = sub.current_period_end.date() if sub else date.today()
    return await svc.get_current_usage(
        workspace_id=workspace_id,
        billing_period_start=period_start,
        billing_period_end=period_end,
    )


@workspace_router.get("/usage/history", response_model=WorkspaceUsageHistoryResponse)
async def get_workspace_usage_history(
    workspace_id: UUID,
    from_date: Optional[date] = Query(None),
    to_date: Optional[date] = Query(None),
    _: User = Depends(get_current_user),
    svc: UsageService = Depends(_get_service),
) -> WorkspaceUsageHistoryResponse:
    return await svc.get_workspace_usage_history(
        workspace_id=workspace_id,
        from_date=from_date,
        to_date=to_date,
    )


# ---------------------------------------------------------------------------
# Cloud internal — AI usage reporting
# ---------------------------------------------------------------------------


@cloud_router.post("/ai", response_model=AIUsageAckResponse)
async def record_ai_usage(
    body: AIUsageReportRequest,
    svc: UsageService = Depends(_get_service),
) -> AIUsageAckResponse:
    """Called by Cloud after every AI embed/complete/search operation."""
    return await svc.record_ai_usage(body)
