"""
Auth commands for NWO CLI
"""

import os
import click
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
import yaml
from pathlib import Path

from ..client import NWOClient, NWOAPIError

console = Console()


@click.group(name="auth")
def auth():
    """
    Authenticate with the NWO Robotics API.
    
    Examples:
        nwo auth login          # Log in with API key
        nwo auth logout         # Remove stored credentials
        nwo auth status         # Check authentication status
    """
    pass


@auth.command(name="login")
def login():
    """Authenticate with your API key."""
    config_dir = Path.home() / ".nwo"
    config_file = config_dir / "config.yaml"
    
    console.print(Panel(
        "[bold]NWO Robotics CLI Authentication[/bold]\n\n"
        "Get your API key from:\n"
        "https://nwo.capital/webapp/api-key.php",
        title="Login",
        border_style="cyan"
    ))
    
    api_key = Prompt.ask("Enter your API key", password=True)
    
    if not api_key.startswith("sk_"):
        console.print("[yellow]Warning:[/yellow] API key should start with 'sk_'")
        if not click.confirm("Continue anyway?"):
            return
    
    # Test the key
    with console.status("[bold green]Validating API key..."):
        try:
            os.environ["NWO_API_KEY"] = api_key
            client = NWOClient()
            result = client.health_check()
            
            if result.get("status") == "ok":
                # Save to config file
                config_dir.mkdir(exist_ok=True)
                config = {"api_key": api_key}
                with open(config_file, "w") as f:
                    yaml.dump(config, f)
                os.chmod(config_file, 0o600)  # Restrict permissions
                
                console.print(f"[bold green]✓ Authentication successful![/bold green]")
                console.print(f"[dim]API Version: {result.get('version', '2.0.0')}[/dim]")
            else:
                console.print(f"[red]✗ API health check failed[/red]")
                
        except NWOAPIError as e:
            console.print(f"[red]✗ Authentication failed:[/red] {e}")
            if "Invalid" in str(e) or "not found" in str(e).lower():
                console.print("[dim]Check your API key at https://nwo.capital/webapp/api-key.php[/dim]")


@auth.command(name="logout")
def logout():
    """Remove stored credentials."""
    config_file = Path.home() / ".nwo" / "config.yaml"
    
    if config_file.exists():
        config_file.unlink()
        console.print("[green]✓ Logged out successfully[/green]")
    else:
        console.print("[yellow]No credentials stored[/yellow]")
    
    # Also clear environment
    if "NWO_API_KEY" in os.environ:
        del os.environ["NWO_API_KEY"]


@auth.command(name="status")
def status():
    """Check authentication status."""
    config_file = Path.home() / ".nwo" / "config.yaml"
    env_key = os.getenv("NWO_API_KEY")
    
    console.print("[bold]Authentication Status:[/bold]\n")
    
    if env_key:
        masked = env_key[:12] + "•" * (len(env_key) - 12)
        console.print(f"  Environment: [green]✓[/green] {masked}")
    else:
        console.print(f"  Environment: [red]✗[/red] Not set")
    
    if config_file.exists():
        console.print(f"  Config file: [green]✓[/green] {config_file}")
    else:
        console.print(f"  Config file: [red]✗[/red] Not found")
    
    # Test the key
    try:
        client = NWOClient()
        result = client.health_check()
        if result.get("status") == "ok":
            console.print(f"\n[green]✓ API connection successful[/green]")
        else:
            console.print(f"\n[red]✗ API connection failed[/red]")
    except NWOAPIError as e:
        console.print(f"\n[red]✗ API connection failed:[/red] {e}")
