"""JWT session tokens — zero dependencies (stdlib only)."""

from __future__ import annotations

import base64
import hashlib
import hmac
import json
import time


def _b64encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def _b64decode(s: str) -> bytes:
    padding = 4 - len(s) % 4
    if padding != 4:
        s += "=" * padding
    return base64.urlsafe_b64decode(s)


def create_token(payload: dict, secret: str) -> str:
    """Create an HS256 JWT from the given payload dict."""
    header = _b64encode(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    body = _b64encode(json.dumps(payload).encode())
    sig = _b64encode(
        hmac.new(secret.encode(), f"{header}.{body}".encode(), hashlib.sha256).digest()
    )
    return f"{header}.{body}.{sig}"


def verify_token(token: str, secret: str) -> dict | None:
    """Verify an HS256 JWT. Returns the payload dict or None."""
    try:
        parts = token.split(".")
        if len(parts) != 3:
            return None
        expected_sig = _b64encode(
            hmac.new(
                secret.encode(), f"{parts[0]}.{parts[1]}".encode(), hashlib.sha256
            ).digest()
        )
        if not hmac.compare_digest(expected_sig, parts[2]):
            return None
        payload = json.loads(_b64decode(parts[1]))
        if payload.get("exp", 0) < int(time.time()):
            return None
        return payload
    except Exception:
        return None


def create_session_token(
    user_id: str, email: str, secret: str, max_age: int = 86400 * 30
) -> str:
    """Create a session JWT for an authenticated user."""
    now = int(time.time())
    return create_token(
        {"sub": user_id, "email": email, "iat": now, "exp": now + max_age},
        secret,
    )
