# app/utils/extensions.py
from flask_login import LoginManager
from flask import session
from dataclasses import dataclass
from typing import Optional
from app.services.appwrite_client import AppwriteAccountClient 

login_manager = LoginManager()

@dataclass
class User:
    id: str
    email: str
    name: Optional[str] = None
    email_verification: bool = False

    def is_active(self): return True
    def is_authenticated(self): return True
    def is_anonymous(self): return False
    def get_id(self): return self.id

@login_manager.user_loader
def load_user(user_id: str) -> Optional[User]:
    # First: use cached profile
    u = session.get("user_profile")
    if u and u.get("$id") == user_id:
        return User(
            id=u["$id"],
            email=u["email"],
            name=u.get("name"),
            email_verification=bool(u.get("emailVerification", False)),
        )

    # Next: use the session secret we stored at login
    secret = session.get("appwrite_cookies")
    if not secret:
        return None

    aw = AppwriteAccountClient(cookies=secret)
    try:
        acc = aw.get_account()
        session["user_profile"] = acc
        return User(
            id=acc["$id"],
            email=acc["email"],
            name=acc.get("name"),
            email_verification=bool(acc.get("emailVerification", False)),
        )
    except Exception:
        return None

def get_client_from_session() -> AppwriteAccountClient:
    secret = session.get("appwrite_cookies")
    if not secret:
        raise RuntimeError("No Appwrite session is available. Please log in.")
    return AppwriteAccountClient(cookies=secret)