import time
from flask import session
from ..services.appwrite_client import AppwriteAccountClient

def ensure_fresh_appwrite_jwt(skew_seconds: int = 120) -> str:
    """
    Returns a valid Appwrite JWT, refreshing it if it's missing or expiring soon.
    Relies on the saved Appwrite session cookie in Flask's session.
    """
    jwt_info = session.get("appwrite_jwt")
    now = int(time.time())

    if jwt_info and isinstance(jwt_info, dict):
        exp = int(jwt_info.get("expire", 0))
        # If token still safely valid, reuse it
        if exp - now > skew_seconds and "jwt" in jwt_info:
            return jwt_info["jwt"]

    # Need to mint a new JWT using the user's Appwrite session cookie
    cookies = session.get("appwrite_cookies")
    if not cookies:
        raise RuntimeError("Missing Appwrite session; user must sign in again.")

    aw = AppwriteAccountClient(cookies=cookies)
    new_jwt = aw.create_jwt()  # -> {"jwt": "...", "expire": <unix>}
    session["appwrite_jwt"] = new_jwt
    return new_jwt["jwt"]