from fastapi import Depends, Header, HTTPException
from jose import jwt, JWTError, ExpiredSignatureError
from sqlalchemy.orm import Session
import os
import logging
import secrets
import time

from database import get_db
import services.quota_service as quota_service

now = int(time.time())

logger = logging.getLogger(__name__)

JWT_SECRET = os.getenv("JWT_SECRET")
JWT_ALGORITHM = "HS256"
ADMIN_API_KEY = os.getenv("ADMIN_API_KEY")


def verify_jwt_token(authorization: str = Header(...)) -> dict:
    if not authorization:
        raise HTTPException(status_code=401, detail="Authorization header missing")

    try:
        scheme, token = authorization.split()

        if scheme.lower() != "bearer":
            raise HTTPException(status_code=401, detail="Invalid auth scheme")

    except ValueError:
        raise HTTPException(status_code=401, detail="Invalid Authorization format")

    try:
        payload = jwt.decode(
            token,
            JWT_SECRET,
            algorithms=[JWT_ALGORITHM],
            options={
                "verify_aud": False,
                "verify_nbf": False
            }
        )

        if not payload.get("company_id"):
            raise HTTPException(status_code=401, detail="Invalid token payload")

        logger.info(f"JWT Verified | company_id={payload.get('company_id')}")

        return payload

    except ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")

    except JWTError as e:
        logger.warning(f"JWT error: {e}")
        raise HTTPException(status_code=401, detail="Invalid token")


def verify_admin_api_key(x_api_key: str | None = Header(None, alias="X-Api-Key")) -> None:
    """Gates the admin/quota-config surface with a static service-to-service
    key (separate trust boundary from the per-user JWT) — the Angular admin
    panel sends this on every /admin/quota/* call."""
    if not ADMIN_API_KEY or not x_api_key or not secrets.compare_digest(x_api_key, ADMIN_API_KEY):
        raise HTTPException(status_code=401, detail="Invalid or missing API key")


def enforce_token_quota(
    db: Session = Depends(get_db),
    user_payload: dict = Depends(verify_jwt_token),
) -> dict:
    """Raises 429 once any configured period has reached 100% of its limit;
    otherwise returns the quota check (including any 80%+ warnings) so the
    route can surface them to the client."""
    check = quota_service.check_quota(db, user_payload.get("user_id"), user_payload.get("role_id"))
    if not check["allowed"]:
        raise HTTPException(status_code=429, detail={
            "error": "quota_exceeded",
            "message": "Token quota exceeded.",
            "breaches": check["breaches"],
        })
    return check