import requests
from rich import print as rprint
from .config import get_config, save_config, clear_config, load_config

# Firebase REST Auth URL (no changes needed here — this talks to Google directly)
_FIREBASE_REST_URL = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword"


def login(email, password):
    """
    Authenticates the user against Firebase REST API.
    On success, saves the token locally and pre-warms the backend env config.
    """
    # To authenticate we need the Firebase apiKey — but we can't call load_config yet
    # (we're not authed). We use a lightweight unauthenticated pre-check to get the apiKey.
    # Instead, we embed the project-level public apiKey lookup via the env.
    # The apiKey itself is non-secret (it's in every web page) and safe to bundle here
    # as the real protection is Firebase's own auth rules.
    from .config import BACKEND_URL
    try:
        # First, fetch Firebase config from backend — we pass no token here,
        # but only the apiKey endpoint is public; /api/env still requires auth.
        # To bootstrap: use a separate lightweight public endpoint for just the apiKey,
        # OR: store the Firebase project's public apiKey in a constant (it's always public).
        # We use the stored apiKey from a prior login if available, else from /api/bootstrap.
        saved = get_config()
        if saved and saved.get("firebase_api_key"):
            api_key = saved["firebase_api_key"]
        else:
            # Fetch the apiKey from the public bootstrap endpoint
            resp = requests.get(f"{BACKEND_URL}/api/bootstrap", timeout=5)
            if resp.status_code != 200:
                rprint("[red]Unable to reach AIGenDB server. Please check your connection.[/red]")
                return {"success": False, "error": "Cannot reach server"}
            api_key = resp.json().get("firebase_api_key", "")

        url = f"{_FIREBASE_REST_URL}?key={api_key}"
        payload = {
            "email": email,
            "password": password,
            "returnSecureToken": True
        }

        response = requests.post(url, json=payload, timeout=10)
        data = response.json()

        if response.status_code == 200:
            token = data["idToken"]
            save_config({
                "token": token,
                "user_id": data["localId"],
                "email": data["email"],
                "firebase_api_key": api_key  # cache for next login bootstrap
            })

            # Pre-warm the env config cache — validates session against backend immediately
            load_config(token)

            return {"success": True, "user": data}
        else:
            error_msg = data.get('error', {}).get('message', '')
            if any(x in error_msg for x in ('USER_NOT_FOUND', 'INVALID_PASSWORD', 'INVALID_LOGIN_CREDENTIALS')):
                rprint("\n[red]No account found or invalid login credentials.[/red]")
                rprint("Please enter a correct email/password or create a new account:")
                rprint("[blue]https://www.aigendb.xyz/signup[/blue]\n")
            else:
                rprint(f"\n[red]Login failed: {error_msg}[/red]")
            return {"success": False, "error": error_msg}

    except Exception as e:
        rprint(f"\n[red]Login failed: {str(e)}[/red]")
        return {"success": False, "error": str(e)}


def logout():
    clear_config()
    rprint("[green]Successfully logged out.\n[/green]")


def is_authenticated():
    config = get_config()
    return bool(config and config.get("token"))


def get_token():
    config = get_config()
    return config.get("token") if config else None
