# -*- coding: utf-8 -*-

"""Configuration and setup commands for RC CLI."""

import typer
from pathlib import Path
from .env_loader import get_env_status, check_configuration, get_config_paths

config_app = typer.Typer(
    name="config",
    help="🔧 Configuration management",
    add_completion=False
)


@config_app.command("show")
def show_config():
    """📋 Show current configuration status."""
    typer.echo("\n🔧 RC CLI Configuration Status\n")
    
    # Check configuration
    is_configured, missing = check_configuration()
    
    if is_configured:
        typer.echo("✅ Configuration is complete!\n")
    else:
        typer.echo("⚠️  Configuration is incomplete\n")
    
    # Show status
    status = get_env_status()
    typer.echo("📋 Environment Variables:")
    for key, value in status.items():
        if value:
            icon = "✅"
            display = value
        else:
            icon = "❌"
            display = "NOT SET"
        typer.echo(f"  {icon} {key}: {display}")
    
    # Show config file locations
    typer.echo("\n📁 Configuration file locations (in priority order):")
    config_paths = get_config_paths()
    for i, path in enumerate(config_paths, 1):
        exists = "✅ EXISTS" if path.exists() else "❌ Not found"
        typer.echo(f"  {i}. {path} - {exists}")
    
    if not is_configured:
        typer.echo("\n💡 To set up configuration:")
        typer.echo("  1. Run: rc config setup")
        typer.echo("  2. Or manually create ~/.rc-cli.env with your settings")


@config_app.command("setup")
def setup_config():
    """🚀 Interactive configuration setup."""
    typer.echo("\n🚀 RC CLI Configuration Setup\n")
    typer.echo("This will help you create a configuration file.")
    typer.echo("Press Ctrl+C at any time to cancel.\n")
    
    # Choose location
    home = Path.home()
    default_path = home / ".rc-cli.env"
    
    typer.echo(f"Configuration will be saved to: {default_path}")
    use_default = typer.confirm("Use this location?", default=True)
    
    if not use_default:
        custom_path = typer.prompt("Enter custom path")
        config_path = Path(custom_path)
    else:
        config_path = default_path
    
    # Gather configuration
    typer.echo("\n📝 GitLab Configuration (for Service Parameters)")
    typer.echo("Leave blank to skip if you don't use this feature.\n")
    
    gitlab_url = typer.prompt(
        "GitLab Base URL",
        default="",
        show_default=False
    )
    
    gitlab_token = ""
    if gitlab_url:
        gitlab_project_id = typer.prompt(
            "GitLab Project ID",
            default="24890"
        )
        gitlab_token = typer.prompt(
            "GitLab Personal Access Token",
            hide_input=True,
            default="",
            show_default=False
        )
    else:
        gitlab_project_id = ""
    
    # Write configuration
    try:
        with open(config_path, 'w', encoding='utf-8') as f:
            f.write("# RC CLI Configuration\n")
            f.write("# Generated by: rc config setup\n\n")
            
            if gitlab_url:
                f.write("# GitLab Configuration for Service Parameters\n")
                f.write(f"SP_GITLAB_BASE_URL={gitlab_url}\n")
                f.write(f"SP_GITLAB_PROJECT_ID={gitlab_project_id}\n")
                if gitlab_token:
                    f.write(f"GITLAB_TOKEN={gitlab_token}\n")
                f.write("\n")
            
            f.write("# Add other environment variables as needed\n")
        
        typer.echo(f"\n✅ Configuration saved to: {config_path}")
        typer.echo("\n💡 Next steps:")
        typer.echo("  - Verify: rc config show")
        typer.echo("  - Test: rc sp list")
        typer.echo(f"  - Edit: {config_path}")
        
    except Exception as e:
        typer.echo(f"\n❌ Error saving configuration: {e}", err=True)
        raise typer.Exit(1)


@config_app.command("validate")
def validate_config():
    """✓ Validate configuration."""
    typer.echo("\n🔍 Validating Configuration...\n")
    
    is_configured, missing = check_configuration()
    
    if is_configured:
        typer.echo("✅ All required configuration is set!")
        typer.echo("\n🎉 You're ready to use RC CLI!")
    else:
        typer.echo("❌ Configuration is incomplete\n")
        typer.echo("Missing or invalid variables:")
        for var in missing:
            typer.echo(f"  - {var}")
        typer.echo("\n💡 Run: rc config setup")
        raise typer.Exit(1)

