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")


_MANAGER_ROLE_VALUES = frozenset({
    "manager", "reporting_manager", "reporting manager",
    "line_manager", "line manager", "team_manager", "team manager",
    "people_manager", "people manager",
    "hr", "hr_manager", "hr manager", "human_resources", "human resources",
})

_ROLE_CLAIMS = ("role", "user_role", "role_name", "user_type")

def extract_role(payload: dict) -> str | None:
    """The caller's role as a normalised lowercase string, or None when the
    token carries no role-bearing claim at all. Only the FIRST claim present
    wins — a token carrying an explicit "role" is never second-guessed by
    the coarser "user_type".

    A purely numeric value is skipped rather than returned: live erp-api
    tokens send user_type as a numeric string ("3"), which is an id, not a
    role NAME. Returning "3" here would be a meaningless answer that reads
    like a real one — None ("the token didn't say") is the truthful result,
    and is what makes the erp-api fallback kick in.
    """
    if not isinstance(payload, dict):
        return None
    for claim in _ROLE_CLAIMS:
        value = payload.get(claim)
        if isinstance(value, str) and value.strip() and not value.strip().isdigit():
            return value.strip().lower()
    return None


def _coerce_role_id(value) -> int | None:
    """Live erp-api tokens send role_id as a STRING ("5"), not an int — an
    isinstance(value, int) check silently made the MANAGER_ROLE_IDS fallback
    dead code against every real token. Booleans are rejected explicitly
    because True == 1 in Python, which would otherwise match role id 1."""
    if isinstance(value, bool):
        return None
    if isinstance(value, int):
        return value
    if isinstance(value, str) and value.strip().isdigit():
        return int(value.strip())
    return None

def _manager_role_ids() -> set[int]:
    """Re-read per call (not frozen at import) for the same test-friendliness
    reason as quota_service._get_timezone()."""
    raw = os.getenv("MANAGER_ROLE_IDS", "")
    ids = set()
    for part in raw.split(","):
        part = part.strip()
        if part.isdigit():
            ids.add(int(part))
    return ids


def is_manager_role(payload: dict) -> bool:
    """True when the JWT itself identifies the caller as a manager.

    This is a fast-path ALLOW, never the authority. A False here does not
    mean "deny" — it means "the token didn't say", which is the normal case
    for every token issued today. Callers fall back to erp-api's
    authoritative is_manager flag (see individual_report.py's role gate),
    exactly as team_leave_query_node already does; erp-api remains the only
    thing enforcing per-employee permission scope either way.
    """
    role = extract_role(payload)
    if role and role in _MANAGER_ROLE_VALUES:
        return True
    return _coerce_role_id((payload or {}).get("role_id")) in _manager_role_ids()

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")


# ── JWT role extraction (FR-07.3) ─────────────────────────────────────────────
# The manager-only individual-report capability needs to know the caller's
# role BEFORE any erp-api call, so an ordinary employee's query never even
# reaches the lookup path.
#
# Important: the JWT this service is issued today carries
# {user_id, company_id, role_id, user_type, company_name, exp} — there is no
# string "role" claim yet (verified against the live token in
# postman/token_quota.postman_collection.json). extract_role() therefore
# reads the first role-bearing claim that IS present, in descending order of
# specificity, so it starts working the moment erp-api begins issuing a
# "role" claim without needing a code change here. MANAGER_ROLE_IDS covers
# the meantime: today's tokens identify role numerically via role_id.
_MANAGER_ROLE_VALUES = frozenset({
    "manager", "reporting_manager", "reporting manager",
    "line_manager", "line manager", "team_manager", "team manager",
    "people_manager", "people manager",
    "hr", "hr_manager", "hr manager", "human_resources", "human resources",
})

_ROLE_CLAIMS = ("role", "user_role", "role_name", "user_type")


def extract_role(payload: dict) -> str | None:
    """The caller's role as a normalised lowercase string, or None when the
    token carries no role-bearing claim at all. Only the FIRST claim present
    wins — a token carrying an explicit "role" is never second-guessed by
    the coarser "user_type".

    A purely numeric value is skipped rather than returned: live erp-api
    tokens send user_type as a numeric string ("3"), which is an id, not a
    role NAME. Returning "3" here would be a meaningless answer that reads
    like a real one — None ("the token didn't say") is the truthful result,
    and is what makes the erp-api fallback kick in.
    """
    if not isinstance(payload, dict):
        return None
    for claim in _ROLE_CLAIMS:
        value = payload.get(claim)
        if isinstance(value, str) and value.strip() and not value.strip().isdigit():
            return value.strip().lower()
    return None


def _manager_role_ids() -> set[int]:
    """Re-read per call (not frozen at import) for the same test-friendliness
    reason as quota_service._get_timezone()."""
    raw = os.getenv("MANAGER_ROLE_IDS", "")
    ids = set()
    for part in raw.split(","):
        part = part.strip()
        if part.isdigit():
            ids.add(int(part))
    return ids


def _coerce_role_id(value) -> int | None:
    """Live erp-api tokens send role_id as a STRING ("5"), not an int — an
    isinstance(value, int) check silently made the MANAGER_ROLE_IDS fallback
    dead code against every real token. Booleans are rejected explicitly
    because True == 1 in Python, which would otherwise match role id 1."""
    if isinstance(value, bool):
        return None
    if isinstance(value, int):
        return value
    if isinstance(value, str) and value.strip().isdigit():
        return int(value.strip())
    return None


def is_manager_role(payload: dict) -> bool:
    """True when the JWT itself identifies the caller as a manager.

    This is a fast-path ALLOW, never the authority. A False here does not
    mean "deny" — it means "the token didn't say", which is the normal case
    for every token issued today. Callers fall back to erp-api's
    authoritative is_manager flag (see individual_report.py's role gate),
    exactly as team_leave_query_node already does; erp-api remains the only
    thing enforcing per-employee permission scope either way.
    """
    role = extract_role(payload)
    if role and role in _MANAGER_ROLE_VALUES:
        return True
    return _coerce_role_id((payload or {}).get("role_id")) in _manager_role_ids()


#: Company-wide administrator role names. Deliberately NOT folded into
#: _MANAGER_ROLE_VALUES: that set is what is_manager_role() answers on, and
#: every manager-gated feature in the graph (leave approval, individual
#: reports, the team queries) keys off that one answer. Adding "admin" there
#: would hand an administrator those capabilities too, silently, as a side
#: effect of a shift-visibility change. Kept separate so widening one does
#: not widen the other.
#:
#: erp-api's /api/v1/ai/leave/context reports is_manager and is_hr but has no
#: is_admin, so an administrator is recognisable from the JWT role claim
#: alone (or numerically, via the MANAGER_ROLE_IDS env list).
_ADMIN_ROLE_VALUES = frozenset({
    "admin", "administrator", "super_admin", "super admin", "superadmin",
    "company_admin", "company admin", "system_admin", "system admin",
})


def is_admin_role(payload: dict) -> bool:
    """True when the JWT itself identifies the caller as an administrator.

    Same contract as is_manager_role: a fast-path ALLOW, never the authority,
    and False means "the token didn't say"."""
    role = extract_role(payload)
    return bool(role and role in _ADMIN_ROLE_VALUES)


def is_privileged_role(payload: dict) -> bool:
    """True when the JWT says the caller is a manager, an HR user, or an
    administrator — the roles allowed to see a team member's record rather
    than only their own.

    One place to ask "is this caller privileged at all", so a feature that
    grants team visibility does not grow its own role vocabulary. Note that
    is_manager_role's own value set already includes the HR role names, so
    this is that answer plus administrators.

    Still a fast-path ALLOW: False means the token carried no role NAME (the
    normal case for tokens that identify role numerically), so a caller
    denied here must be re-checked against erp-api's authoritative
    is_manager/is_hr flags before anything is actually refused.
    """
    return is_manager_role(payload) or is_admin_role(payload)


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