"""
Credits API endpoint - Get user's enrichment credit balance.
Shows purchased credits (never expire) and monthly credits (reset monthly).
"""

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

from ...auth_core import get_current_identity
from ...db import get_session
from ...services.credit_manager import get_credit_balance as get_balance
from ...middleware.quota_checker import get_quota

log = logging.getLogger(__name__)

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


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

    Get current enrichment credit balance for the authenticated user.

    Credits are consumed in this order:
    1. Purchased credits first (never expire)
    2. Monthly credits second (reset each month)

    Returns:
        - balance: Total available credits (purchased + monthly)
        - purchased_credits: Credits from one-time purchases (never expire)
        - monthly_credits_limit: Total monthly credits from subscription
        - monthly_credits_used: How many monthly credits consumed this period
        - monthly_credits_remaining: Monthly credits left this period
        - next_reset_at: When monthly credits will reset next

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

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

    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:
        # Use credit manager service for consistent logic
        balance = await get_balance(str(account_id), db)

        # Get quota for reset date
        quota = await get_quota(str(account_id), db)

        return {
            "ok": True,
            "data": {
                "balance": balance["total"],
                "purchased_credits": balance["purchased"],
                "monthly_credits_limit": balance["monthly_limit"],
                "monthly_credits_used": balance["monthly_used"],
                "monthly_credits_remaining": balance["monthly"],
                "next_reset_at": quota.reset_at.isoformat() if quota.reset_at else None,
            },
        }

    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(404, str(e))
    except Exception as e:
        log.error(
            f"Failed to get credit balance for account {account_id}: {e}", exc_info=True
        )
        raise HTTPException(500, f"Failed to get credit balance: {e}")
