"""
Quota API endpoint for Google Sheets integration
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Dict, Any
from datetime import datetime, timedelta
import logging

from ...auth_core import get_current_identity
from ...db import get_session
from ...middleware.quota_checker import get_quota

log = logging.getLogger(__name__)

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


@router.get("")
async def get_quota_status(
    identity: dict = Depends(get_current_identity),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    """
    DEPRECATED: Use /api/v2/usage instead.

    Get current quota usage and limits for the authenticated user.
    Used by Google Sheets add-on to display quota bars and upgrade prompts.

    Authentication: Requires Clerk Bearer token (user's JWT from login)
    """
    import warnings

    warnings.warn(
        "API v1/quota is deprecated. Use /api/v2/usage instead.",
        DeprecationWarning,
        stacklevel=2,
    )
    log.warning(
        f"[DEPRECATED] /api/v1/quota called by account {identity.get('org_id')}. Migrate to /api/v2/usage"
    )

    account_id = identity.get("org_id")  # Use org_id from Clerk token
    if not account_id:
        raise HTTPException(401, "Missing org_id in token")

    try:
        quota = await get_quota(str(account_id), db)
        limits = quota.get_limits()

        now = datetime.utcnow()
        period = now.strftime("%Y-%m")

        # Core usage metrics
        rows_used = quota.monthly_rows_used
        rows_limit = limits["monthly_rows"]
        remaining = max(0, rows_limit - rows_used)
        percentage = int((rows_used / rows_limit * 100)) if rows_limit > 0 else 0

        # Determine warning level
        warning = None
        if percentage >= 90:
            warning = "critical"
        elif percentage >= 75:
            warning = "warning"

        # Calculate reset timing
        reset_at = quota.reset_at
        delta = reset_at - now
        if delta.total_seconds() < 0:
            delta = timedelta(0)

        days_until_reset = delta.days
        hours_until_reset = (delta.seconds // 3600) % 24

        reset_in_str = f"{days_until_reset}d {hours_until_reset}h"
        reset_date_str = reset_at.strftime("%b %d, %Y")

        tier_details = {
            "name": quota.tier,
            "monthly_row_credits": limits["monthly_rows"],
            "concurrent_jobs": limits.get("concurrent_jobs", 1),
            "candidate_cap": limits.get("candidate_cap", 2000),
            "require_b2c": limits.get("require_b2c", False),
            "allow_advanced": limits.get("allow_advanced_algos", True),
            "max_schedules": limits.get("max_schedules", 1),
            "soql_runs_per_month": limits.get("soql_runs_per_month"),
        }

        return {
            "ok": True,
            "data": {
                "period": period,
                "used": rows_used,
                "limit": rows_limit,
                "remaining": remaining,
                "resetAt": reset_at.isoformat(),
                "resetDate": reset_date_str,
                "resetIn": reset_in_str,
                "tier": quota.tier,
                "status": "active",
                "percentage": percentage,
                "warning": warning,
                "credits": {
                    "used": quota.enrichment_credits_used,
                    "limit": limits["enrichment_credits"],
                    "remaining": max(
                        0, limits["enrichment_credits"] - quota.enrichment_credits_used
                    ),
                },
                "tierDetails": tier_details,
            },
        }

    except Exception as e:
        log.error(f"Failed to get quota for account {account_id}: {e}")
        raise HTTPException(500, f"Failed to get quota: {e}")
