import os
import json
import sys
import requests
from pathlib import Path

CONFIG_DIR = Path.home() / '.aigendb'
CONFIG_FILE = CONFIG_DIR / 'config.json'

# Backend base URL — set AIGENDB_API env var in production to point to your deployed backend
BACKEND_URL = os.getenv("AIGENDB_API", "http://127.0.0.1:8000")

_cached_env_config = None


def load_config(token=None):
    """
    Fetches /api/env from the backend, authenticated with the user's Firebase ID token.
    The backend will reject requests without a valid token (401).

    Args:
        token (str | None): Firebase ID token. If None, reads from saved config file.
    """
    global _cached_env_config
    if _cached_env_config is not None:
        return _cached_env_config

    # Resolve token: use provided token or fall back to saved config
    auth_token = token
    if not auth_token:
        saved = get_config()
        auth_token = saved.get("token") if saved else None

    if not auth_token:
        from rich import print as rprint
        rprint("\n[red]Not authenticated. Please log in first.[/red]")
        sys.exit(1)

    try:
        response = requests.get(
            f"{BACKEND_URL}/api/env",
            timeout=10,
            headers={
                "Authorization": f"Bearer {auth_token}",
                "Content-Type": "application/json"
            }
        )

        if response.status_code == 200:
            _cached_env_config = response.json()
            return _cached_env_config

        if response.status_code == 401:
            from rich import print as rprint
            rprint("\n[yellow]Your session has expired or is invalid. Please log in again.[/yellow]")
            clear_config()
            sys.exit(1)

        from rich import print as rprint
        rprint(f"\n[red]Backend returned error {response.status_code}. Please try again later.[/red]")
        sys.exit(1)

    except requests.exceptions.ConnectionError:
        from rich import print as rprint
        rprint("\n[red]Unable to connect to AIGenDB server. Is the backend running?[/red]")
        sys.exit(1)
    except Exception as e:
        from rich import print as rprint
        rprint(f"\n[red]Unexpected error fetching config: {str(e)}[/red]")
        sys.exit(1)


def clear_env_cache():
    """Clears the in-memory env config cache (useful after logout)."""
    global _cached_env_config
    _cached_env_config = None


def get_config():
    if CONFIG_FILE.exists():
        try:
            with open(CONFIG_FILE, 'r') as f:
                return json.load(f)
        except Exception:
            return None
    return None


def save_config(config):
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f, indent=2)


def clear_config():
    clear_env_cache()
    if CONFIG_FILE.exists():
        CONFIG_FILE.unlink()
