"""Configuration management for RoastBuddy."""

import os
import yaml
from pathlib import Path
from typing import Dict, Any
from rich.console import Console
from rich.table import Table

console = Console()

DEFAULT_CONFIG = {
    "roast_intensity": "medium",  # light, medium, spicy
    "auto_roast_on_commit": False,
    "use_copilot": "auto",  # auto, always, never
    "enable_streaks": True,
    "show_emojis": True,
    "color_output": True,
}

CONFIG_DIR = Path.home() / ".roastbuddy"
CONFIG_FILE = CONFIG_DIR / "config.yaml"


def get_config_dir() -> Path:
    """Get or create the RoastBuddy config directory."""
    CONFIG_DIR.mkdir(exist_ok=True)
    return CONFIG_DIR


def get_config_file() -> Path:
    """Get the config file path."""
    return CONFIG_FILE


def load_config() -> Dict[str, Any]:
    """Load configuration from file or return defaults."""
    if not CONFIG_FILE.exists():
        return DEFAULT_CONFIG.copy()
    
    try:
        with open(CONFIG_FILE, "r") as f:
            config = yaml.safe_load(f) or {}
        return {**DEFAULT_CONFIG, **config}
    except Exception as e:
        console.print(f"[yellow]Warning: Failed to load config: {e}[/yellow]")
        return DEFAULT_CONFIG.copy()


def save_config(config: Dict[str, Any]) -> bool:
    """Save configuration to file."""
    try:
        get_config_dir()
        with open(CONFIG_FILE, "w") as f:
            yaml.dump(config, f, default_flow_style=False)
        return True
    except Exception as e:
        console.print(f"[red]Error saving config: {e}[/red]")
        return False


def show_config():
    """Display current configuration."""
    config = load_config()
    
    table = Table(title="RoastBuddy Configuration")
    table.add_column("Setting", style="cyan")
    table.add_column("Value", style="green")
    
    for key, value in config.items():
        table.add_row(key, str(value))
    
    console.print(table)
    console.print(f"\n📁 Config file: [cyan]{CONFIG_FILE}[/cyan]")


def set_config(key: str, value: str):
    """Set a configuration value."""
    config = load_config()
    
    # Type conversion
    if value.lower() in ["true", "false"]:
        value = value.lower() == "true"
    
    config[key] = value
    
    if save_config(config):
        console.print(f"[green]✅ Set {key} = {value}[/green]")
    else:
        console.print(f"[red]❌ Failed to set configuration[/red]")


def get_config_value(key: str, default: Any = None) -> Any:
    """Get a single configuration value."""
    config = load_config()
    return config.get(key, default)
