from __future__ import annotations

import base64
import json
from datetime import datetime, timezone


def decode_session_cookie(cookie_value: str) -> dict:
    """Декодирует PLAY2AUTH_SESS_ID → JSON"""
    padded = cookie_value + "=" * (-len(cookie_value) % 4)
    data = base64.urlsafe_b64decode(padded).decode("utf-8")
    return json.loads(data)


def extract_expiration_from_session(cookie_value: str) -> datetime | None:
    """Извлекает expirationDateTime из куки и возвращает datetime в UTC"""
    try:
        session_data = decode_session_cookie(cookie_value)
        exp_str = session_data.get("expirationDateTime", "").split("[")[0]
        if not exp_str:
            return None
        dt = datetime.fromisoformat(exp_str)
        if dt.tzinfo:
            dt = dt.astimezone(timezone.utc)
        return dt.replace(tzinfo=timezone.utc)
    except Exception:
        return None
