from typing import List
"""
CLI commands for metadata profile discovery and management.

Provides commands to list, inspect, and validate metadata profiles
that are used for generating realistic cloud resource metadata.
"""

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

from ..profiles.metadata import (
    get_profile,
    get_profile_info,
    get_profile_values,
    list_profiles,
)

console = Console()

app = typer.Typer(
    help="Manage and explore metadata profiles for realistic cloud resource generation."
)


@app.command("list")
def list_profiles_cmd():
    """List all available metadata profiles."""
    profiles = list_profiles()

    table = Table(
        title="Available Metadata Profiles", show_header=True, header_style="bold blue"
    )
    table.add_column("Profile Name", style="cyan", no_wrap=True)
    table.add_column("Canonical Values", style="green")
    table.add_column("Total Variants", style="yellow")
    table.add_column("Avg Variants", style="magenta")

    for profile_name in sorted(profiles):
        info = get_profile_info(profile_name)
        table.add_row(
            profile_name,
            str(info["canonical_count"]),
            str(info["total_variants"]),
            str(info["avg_variants_per_value"]),
        )

    console.print(table)
    console.print(
        "\n💡 Use [bold cyan]czbillgen metadata show <profile>[/bold cyan] to see details"
    )


@app.command()
def show(profile_name: str):
    """Show detailed information about a specific metadata profile.

    PROFILE_NAME: Name of the metadata profile to inspect
    """
    try:
        profile_data = get_profile(profile_name)
        info = get_profile_info(profile_name)

        # Profile summary
        summary_text = Text()
        summary_text.append("Profile: ", style="bold")
        summary_text.append(f"{profile_name}\n", style="bold cyan")
        summary_text.append("Canonical Values: ", style="bold")
        summary_text.append(f"{info['canonical_count']}\n", style="green")
        summary_text.append("Total Variants: ", style="bold")
        summary_text.append(f"{info['total_variants']}\n", style="yellow")
        summary_text.append("Average Variants per Value: ", style="bold")
        summary_text.append(f"{info['avg_variants_per_value']}", style="magenta")

        console.print(Panel(summary_text, title="Profile Summary", border_style="blue"))

        # Detailed values and variants table
        table = Table(
            title=f"{profile_name.title()} Values and Variants",
            show_header=True,
            header_style="bold blue",
        )
        table.add_column("Canonical Value", style="bold green", no_wrap=True)
        table.add_column("Variants", style="dim")
        table.add_column("Count", style="yellow", justify="center")

        for canonical_value, data in profile_data.items():
            variants = data["variants"]
            # Truncate long variant lists for display
            if len(variants) > 6:
                display_variants = (
                    ", ".join(variants[:6]) + f" ... (+{len(variants) - 6} more)"
                )
            else:
                display_variants = ", ".join(variants)

            table.add_row(canonical_value, display_variants, str(len(variants)))

        console.print("\n")
        console.print(table)

        # Usage example
        canonical_keys = [k for k in profile_data.keys()]
        example_key1 = canonical_keys[0]
        example_variant1 = profile_data[example_key1]["variants"][0]

        if len(canonical_keys) > 1:
            example_key2 = canonical_keys[1]
            example_variant2 = profile_data[example_key2]["variants"][0]
        else:
            example_key2 = example_key1
            example_variant2 = (
                profile_data[example_key1]["variants"][1]
                if len(profile_data[example_key1]["variants"]) > 1
                else example_variant1
            )

        usage_text = f"""[bold]Usage in generate config:[/bold]

[dim]# Apply {profile_name} profile with realistic variants[/dim]
[cyan]metadata_profile: "{profile_name}"[/cyan]

[dim]# This will randomly assign canonical values and variants like:[/dim]
[green]• {example_key1} → {example_variant1}[/green]
[green]• {example_key2} → {example_variant2}[/green]"""

        console.print(Panel(usage_text, title="Usage Example", border_style="green"))

    except KeyError as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        console.print(
            "\n💡 Use [bold cyan]czbillgen metadata List[/bold cyan] to see available profiles"
        )


@app.command()
def values(
    profile_name: str,
    canonical_only: bool = typer.Option(
        False, "--canonical-only", help="Show only canonical values, not variants"
    ),
):
    """List all values in a metadata profile.

    PROFILE_NAME: Name of the metadata profile
    """
    try:
        if canonical_only:
            values_list = get_profile_values(profile_name)
            console.print(
                f"[bold cyan]{profile_name.title()} - Canonical Values:[/bold cyan]"
            )
            for value in sorted(values_list):
                console.print(f"  • {value}")
        else:
            profile_data = get_profile(profile_name)
            console.print(
                f"[bold cyan]{profile_name.title()} - All Values (Canonical + Variants):[/bold cyan]"
            )

            for canonical_value in sorted(profile_data.keys()):
                console.print(f"\n[bold green]{canonical_value}:[/bold green]")
                console.print(f"  [dim]canonical:[/dim] {canonical_value}")
                for variant in profile_data[canonical_value]["variants"]:
                    console.print(f"  [dim]variant:[/dim] {variant}")

    except KeyError as e:
        console.print(f"[bold red]Error:[/bold red] {e}")


@app.command()
def validate():
    """Validate all metadata profiles for consistency and correctness."""
    profiles = list_profiles()
    console.print("[bold blue]Validating metadata profiles...[/bold blue]\n")

    issues_found = 0

    for profile_name in profiles:
        try:
            profile_data = get_profile(profile_name)
            profile_issues = []

            # Check for empty profiles
            if not profile_data:
                profile_issues.append("Profile is empty")

            # Check each canonical value
            for canonical_value, data in profile_data.items():
                if not isinstance(data, dict):
                    profile_issues.append(
                        f"'{canonical_value}': Invalid data structure"
                    )
                    continue

                if "variants" not in data:
                    profile_issues.append(
                        f"'{canonical_value}': Missing 'variants' key"
                    )
                    continue

                variants = data["variants"]
                if not isinstance(variants, list):
                    profile_issues.append(
                        f"'{canonical_value}': 'variants' must be a list"
                    )
                    continue

                if len(variants) == 0:
                    profile_issues.append(f"'{canonical_value}': Empty variants list")

                # Check for duplicate variants
                if len(variants) != len(set(variants)):
                    duplicates = [v for v in variants if variants.count(v) > 1]
                    profile_issues.append(
                        f"'{canonical_value}': Duplicate variants: {duplicates}"
                    )

            # Report results for this profile
            if profile_issues:
                console.print(f"[bold red]❌ {profile_name}:[/bold red]")
                for issue in profile_issues:
                    console.print(f"   • {issue}")
                issues_found += len(profile_issues)
            else:
                info = get_profile_info(profile_name)
                console.print(
                    f"[bold green]✅ {profile_name}:[/bold green] {info['canonical_count']} values, {info['total_variants']} variants"
                )

        except Exception as e:
            console.print(
                f"[bold red]❌ {profile_name}:[/bold red] Validation error: {e}"
            )
            issues_found += 1

    # Summary
    console.print("\n" + "=" * 50)
    if issues_found == 0:
        console.print("[bold green]✅ All metadata profiles are valid![/bold green]")
    else:
        console.print(
            f"[bold red]❌ Found {issues_found} issues across {len(profiles)} profiles[/bold red]"
        )
        console.print("Please fix the issues above before using the profiles.")


# App is exported as 'app' for use in main CLI
