"""Configuration commands for manta-client CLI."""

from __future__ import annotations

import typer

from manta_client.config import config_manager
from manta_client.output import console, print_error, print_key_value, print_success

app = typer.Typer(help="Configuration management")


@app.command("show")
def show_config(
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
) -> None:
    """Show current configuration."""
    config = config_manager.load_config()
    data = config.to_dict()

    # Mask sensitive data
    if data.get("access_token"):
        token = data["access_token"]
        if len(token) > 20:
            data["access_token"] = token[:10] + "..." + token[-10:]

    if json_output:
        from manta_client.output import print_json

        print_json(data)
    else:
        console.print(f"\n[bold]Configuration file:[/bold] {config_manager.config_path}")
        print_key_value(data, title="Current settings")
        console.print()


@app.command("set")
def set_config(
    key: str = typer.Argument(..., help="Configuration key (e.g., 'api_url')"),
    value: str = typer.Argument(..., help="Configuration value"),
) -> None:
    """Set a configuration value.

    Available keys:
    - api_url: Manta API server URL
    - access_token: Authentication token
    - session_uuid: Session UUID
    - user_id: User ID
    - username: Username
    """
    valid_keys = [
        "api_url",
        "access_token",
        "refresh_token",
        "session_uuid",
        "user_id",
        "username",
    ]

    if key not in valid_keys:
        print_error(f"Invalid key: {key}\nValid keys: {', '.join(valid_keys)}")
        raise typer.Exit(1)

    # Validate URL fields cannot be empty
    url_keys = {"api_url"}
    if key in url_keys and not value.strip():
        print_error(f"'{key}' cannot be empty")
        raise typer.Exit(1)

    success = config_manager.set_value(key, value)
    if success:
        print_success(f"Configuration '{key}' updated successfully.")
    else:
        print_error(f"Failed to set configuration '{key}'")
        raise typer.Exit(1)


@app.command("path")
def show_path() -> None:
    """Show configuration file path."""
    console.print(f"{config_manager.config_path}")
