"""
========================================
CV6 AI Trading OS
JWT Authentication
========================================
"""

import os
from datetime import datetime, timedelta, timezone

from dotenv import load_dotenv
from jose import jwt

# Load .env directly rather than relying on some other module having
# already called load_dotenv() first — this module must be safe to
# import on its own, independent of app-wide import order.
load_dotenv()

# =========================================
# JWT Configuration
#
# M-2 FIX: fail fast instead of silently falling back to a hardcoded
# secret if SECRET_KEY is ever missing from the environment — a shared
# hardcoded fallback would let anyone forge valid JWTs.
# =========================================

SECRET_KEY = os.getenv("SECRET_KEY")
if not SECRET_KEY:
    raise RuntimeError(
        "SECRET_KEY environment variable is not set. "
        "Refusing to start with a hardcoded/default JWT signing secret."
    )

ALGORITHM = "HS256"

ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))

# =========================================
# Create Access Token
# =========================================

def create_access_token(data: dict):

    to_encode = data.copy()

    expire = datetime.now(timezone.utc) + timedelta(
        minutes=ACCESS_TOKEN_EXPIRE_MINUTES
    )

    to_encode.update(
        {
            "exp": expire
        }
    )

    return jwt.encode(
        to_encode,
        SECRET_KEY,
        algorithm=ALGORITHM
    )


# =========================================
# Verify Token
# =========================================

def verify_token(token: str):

    payload = jwt.decode(
        token,
        SECRET_KEY,
        algorithms=[ALGORITHM]
    )

    return payload