from datetime import datetime
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, ConfigDict
from sqlalchemy.orm import Session

from database import get_db
from dependencies import verify_admin_api_key
from models.quota_policy import QuotaPolicy
import services.quota_service as quota_service

router = APIRouter(
    prefix="/admin/quota",
    tags=["admin-quota"],
    dependencies=[Depends(verify_admin_api_key)],
)

_VALID_SCOPES = {"default", "role", "user"}


class QuotaPolicyIn(BaseModel):
    scope_type: str
    scope_id: Optional[int] = None
    daily_token_limit: Optional[int] = None
    weekly_token_limit: Optional[int] = None
    monthly_token_limit: Optional[int] = None
    is_active: bool = True
    updated_by: Optional[int] = None


class QuotaPolicyPatch(BaseModel):
    daily_token_limit: Optional[int] = None
    weekly_token_limit: Optional[int] = None
    monthly_token_limit: Optional[int] = None
    is_active: Optional[bool] = None
    updated_by: Optional[int] = None


class QuotaPolicyOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    scope_type: str
    scope_id: Optional[int] = None
    daily_token_limit: Optional[int] = None
    weekly_token_limit: Optional[int] = None
    monthly_token_limit: Optional[int] = None
    is_active: bool
    updated_by: Optional[int] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None


def _validate_scope(scope_type: str, scope_id: Optional[int]) -> None:
    if scope_type not in _VALID_SCOPES:
        raise HTTPException(status_code=400, detail=f"scope_type must be one of {sorted(_VALID_SCOPES)}")
    if scope_type == "default" and scope_id is not None:
        raise HTTPException(status_code=400, detail="scope_id must be omitted for scope_type='default'")
    if scope_type != "default" and scope_id is None:
        raise HTTPException(status_code=400, detail="scope_id is required unless scope_type='default'")


@router.get("/policies", response_model=list[QuotaPolicyOut])
async def list_policies(
    scope_type: Optional[str] = Query(None),
    is_active: Optional[bool] = Query(None),
    db: Session = Depends(get_db),
):
    query = db.query(QuotaPolicy)
    if scope_type is not None:
        query = query.filter(QuotaPolicy.scope_type == scope_type)
    if is_active is not None:
        query = query.filter(QuotaPolicy.is_active == is_active)
    return query.order_by(QuotaPolicy.id).all()


@router.post(
    "/policies",
    response_model=QuotaPolicyOut,
    status_code=201,
    responses={
        409: {"description": "Duplicate active policy exists for this scope"},
        400: {"description": "Invalid scope_type or missing scope_id"},
    },
)
async def create_policy(body: QuotaPolicyIn, db: Session = Depends(get_db)):
    _validate_scope(body.scope_type, body.scope_id)

    existing = db.query(QuotaPolicy).filter_by(
        scope_type=body.scope_type, scope_id=body.scope_id, is_active=True
    ).first()
    if existing:
        scope_label = (
            f"scope_type='{body.scope_type}', scope_id={body.scope_id}"
            if body.scope_id is not None
            else f"scope_type='{body.scope_type}'"
        )
        raise HTTPException(
            status_code=409,
            detail={
                "error": "duplicate_policy",
                "message": f"An active policy already exists for {scope_label} (id={existing.id}). "
                           f"PATCH /admin/quota/policies/{existing.id} to update it, or "
                           f"DELETE it first to create a new one.",
                "existing_policy_id": existing.id,
            },
        )

    policy = QuotaPolicy(**body.model_dump())
    db.add(policy)
    db.commit()
    db.refresh(policy)
    return policy


@router.patch("/policies/{policy_id}", response_model=QuotaPolicyOut)
async def update_policy(policy_id: int, body: QuotaPolicyPatch, db: Session = Depends(get_db)):
    policy = db.query(QuotaPolicy).filter_by(id=policy_id).first()
    if not policy:
        raise HTTPException(status_code=404, detail="Policy not found")

    for field, value in body.model_dump(exclude_unset=True).items():
        setattr(policy, field, value)

    db.commit()
    db.refresh(policy)
    return policy


@router.delete("/policies/{policy_id}")
async def delete_policy(policy_id: int, db: Session = Depends(get_db)):
    """Soft-deletes by setting is_active=False — historical policy rows are
    kept (e.g. for usage-report auditing) rather than being removed, mirroring
    the same soft-delete convention used for conversations."""
    policy = db.query(QuotaPolicy).filter_by(id=policy_id, is_active=True).first()
    if not policy:
        raise HTTPException(status_code=404, detail="Policy not found")
    policy.is_active = False
    db.commit()
    return {"success": True, "message": f"Policy {policy_id} deleted"}


@router.get("/usage-report")
async def usage_report(
    user_id: Optional[int] = Query(None),
    role_id: Optional[int] = Query(None),
    date_from: Optional[datetime] = Query(None),
    date_to: Optional[datetime] = Query(None),
    db: Session = Depends(get_db),
):
    data = quota_service.usage_report(
        db, user_id=user_id, role_id=role_id, date_from=date_from, date_to=date_to
    )
    return {
        "success": True,
        "filters": {
            "user_id": user_id, "role_id": role_id,
            "date_from": date_from, "date_to": date_to,
        },
        "data": data,
    }
