"""
auth.py — Login flow: prompt endpoint + API key, test connection, save.
"""

import getpass
import sys

import requests
from rich.console import Console
from rich.prompt import Prompt
from rich.panel import Panel
from rich import print as rprint

from onefirewall_ai.config import load_access, save_access

console = Console()

DEFAULT_ENDPOINT = "https://onefirewall.ai"


def _test_connection(endpoint: str, api_key: str) -> tuple[bool, str]:
    """
    Send a minimal chat request to verify the endpoint + key combo.
    Returns (success: bool, message: str).
    """
    url = endpoint.rstrip("/") + "/api/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    payload = {
        "model": "openai/gpt-4o",
        "messages": [{"role": "user", "content": "ping"}],
        "stream": False,
    }
    try:
        resp = requests.post(url, headers=headers, json=payload, timeout=15)
        if resp.status_code == 200:
            return True, "Connection successful ✓"
        elif resp.status_code == 401:
            return False, "Invalid API key (401 Unauthorized)"
        elif resp.status_code == 403:
            return False, "Access forbidden (403) — check your API key permissions"
        elif resp.status_code == 404:
            return False, f"Endpoint not found (404) — is '{endpoint}' correct?"
        else:
            return False, f"Unexpected response: HTTP {resp.status_code} — {resp.text[:200]}"
    except requests.exceptions.ConnectionError:
        return False, f"Cannot connect to '{endpoint}' — is the server running?"
    except requests.exceptions.Timeout:
        return False, "Connection timed out after 15 seconds"
    except Exception as exc:
        return False, f"Unexpected error: {exc}"


def login() -> None:
    """Interactive login: prompt endpoint, API key, test, then save."""
    console.print()
    console.print(Panel(
        "[bold cyan]OneFirewall AI — Login[/bold cyan]\n"
        "[dim]Set up your endpoint and API key to start chatting.[/dim]",
        border_style="cyan",
    ))
    console.print()

    # ── Step 1: Endpoint ──────────────────────────────────────────────────────
    existing = load_access()
    current_endpoint = existing.get("endpoint") or DEFAULT_ENDPOINT

    endpoint = Prompt.ask(
        "[bold]API Endpoint[/bold]",
        default=current_endpoint,
        console=console,
    ).strip().rstrip("/")

    # normalise — add https:// if scheme missing
    if endpoint and not endpoint.startswith(("http://", "https://")):
        endpoint = "https://" + endpoint

    # ── Step 2: API Key ───────────────────────────────────────────────────────
    console.print()
    console.print("[dim]Get your API key from the Profile page on the dashboard.[/dim]")
    try:
        api_key = getpass.getpass("API Key (hidden): ").strip()
    except (KeyboardInterrupt, EOFError):
        console.print("\n[yellow]Login cancelled.[/yellow]")
        sys.exit(0)

    if not api_key:
        console.print("[red]✗ API key cannot be empty.[/red]")
        sys.exit(1)

    # ── Step 3: Test connection ───────────────────────────────────────────────
    console.print()
    with console.status("[bold cyan]Testing connection…[/bold cyan]", spinner="dots"):
        ok, msg = _test_connection(endpoint, api_key)

    if ok:
        console.print(f"[bold green]✓ {msg}[/bold green]")
    else:
        console.print(f"[bold red]✗ {msg}[/bold red]")
        console.print("[dim]Please check your endpoint and API key and try again.[/dim]")
        sys.exit(1)

    # ── Step 4: Save ──────────────────────────────────────────────────────────
    data = {**existing, "endpoint": endpoint, "api_key": api_key}
    save_access(data)

    console.print()
    console.print(Panel(
        f"[bold green]Logged in successfully![/bold green]\n"
        f"[dim]Endpoint:[/dim] [cyan]{endpoint}[/cyan]\n"
        f"[dim]Config saved to:[/dim] [cyan]~/.onefirewall-ai/access.json[/cyan]",
        border_style="green",
    ))
    console.print()
    console.print("[dim]Run [bold]onefirewall-ai hello![/bold] to start chatting.[/dim]")
    console.print()
