"""
Config commands for NWO CLI
"""

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

console = Console()


@click.group(name="config")
def config():
    """
    Manage CLI configuration.
    
    Examples:
        nwo config show          # Show current configuration
        nwo config set key value # Set a configuration value
    """
    pass


@config.command(name="show")
def show_config():
    """Display current configuration."""
    config_file = Path.home() / ".nwo" / "config.yaml"
    
    console.print(Panel(
        f"[bold]Configuration File:[/bold] {config_file}",
        title="Config",
        border_style="cyan"
    ))
    
    if config_file.exists():
        with open(config_file) as f:
            config = yaml.safe_load(f)
        
        if config:
            for key, value in config.items():
                if key == "api_key" and value:
                    value = value[:12] + "•" * (len(value) - 12)
                console.print(f"  {key}: {value}")
        else:
            console.print("  [dim]Empty configuration[/dim]")
    else:
        console.print("  [dim]No configuration file found[/dim]")
        console.print(f"\nRun [cyan]nwo auth login[/cyan] to create one.")


@config.command(name="set")
@click.argument("key")
@click.argument("value")
def set_config(key, value):
    """Set a configuration value."""
    config_file = Path.home() / ".nwo" / "config.yaml"
    config_dir = config_file.parent
    
    config_dir.mkdir(exist_ok=True)
    
    # Load existing config
    if config_file.exists():
        with open(config_file) as f:
            config = yaml.safe_load(f) or {}
    else:
        config = {}
    
    config[key] = value
    
    with open(config_file, "w") as f:
        yaml.dump(config, f)
    
    console.print(f"[green]✓ Set {key} = {value}[/green]")


@config.command(name="get")
@click.argument("key")
def get_config(key):
    """Get a configuration value."""
    config_file = Path.home() / ".nwo" / "config.yaml"
    
    if not config_file.exists():
        console.print("[red]No configuration file found[/red]")
        return
    
    with open(config_file) as f:
        config = yaml.safe_load(f) or {}
    
    value = config.get(key)
    if value:
        console.print(value)
    else:
        console.print(f"[yellow]Key '{key}' not found[/yellow]")
