"""CNP Solutions platform operator (God Mode) — separate from tenant super_admin."""
from __future__ import annotations

from datetime import timedelta
from typing import Any, Dict, Optional

from fastapi import Depends, Header, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from app.core.config import settings
from app.core.security import create_access_token, verify_token

PLATFORM_SUB = "platform@cnpsolutions.internal"
_platform_bearer = HTTPBearer(auto_error=False)


def effective_platform_admin_secret() -> Optional[str]:
    return (settings.platform_admin_secret or settings.license_admin_secret or "").strip() or None


def create_platform_access_token(hours: Optional[int] = None) -> str:
    """
    Issue God Mode JWT. hours <= 0 (default) = no practical expiry (~100 years).
    The platform access code (PLATFORM_ADMIN_SECRET) never expires on its own.
    """
    if hours is None:
        hours = int(settings.platform_admin_token_hours or 0)
    if hours <= 0:
        expires_delta = timedelta(days=36525)
    else:
        expires_delta = timedelta(hours=min(int(hours), 8760))
    return create_access_token(
        {
            "sub": PLATFORM_SUB,
            "role": "platform_operator",
            "platform_admin": True,
            "company_id": None,
            "branch_id": None,
        },
        expires_delta=expires_delta,
    )


def verify_platform_secret(secret: str) -> bool:
    expected = effective_platform_admin_secret()
    if not expected:
        return False
    return secret == expected


def _payload_is_platform_admin(payload: Dict[str, Any]) -> bool:
    return payload.get("platform_admin") is True and payload.get("sub") == PLATFORM_SUB


def require_platform_admin(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(_platform_bearer),
    x_platform_admin_key: Optional[str] = Header(None, alias="X-Platform-Admin-Key"),
) -> Dict[str, Any]:
    """
    Platform God Mode access — JWT from POST /platform/auth/login or header secret per request.
    Tenant users (including super_admin) cannot access platform routes.
    """
    if x_platform_admin_key and verify_platform_secret(x_platform_admin_key):
        return {"sub": PLATFORM_SUB, "platform_admin": True, "via": "header"}

    if not credentials:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Platform operator authentication required",
        )

    payload = verify_token(credentials.credentials)
    if not payload or not _payload_is_platform_admin(payload):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Platform operator access only",
        )
    return payload
