from typing import Optional
"""
Profile listing commands for unified profile system.
"""

import typer

from profiles import registry
from ..common import BaseCommand, display_summary_table


class ProfileListCommand(BaseCommand):
    """Profile listing command for unified profile system."""

    def list_all_profiles(self, profile_type: Optional[str] = None):
        """List all available profiles."""
        try:
            if profile_type:
                # List specific profile type
                if profile_type not in registry.get_profile_types():
                    valid_types = ", ".join(registry.get_profile_types())
                    self.console.print(
                        f"[red]Invalid profile type: {profile_type}[/red]"
                    )
                    self.console.print(f"[blue]Valid types: {valid_types}[/blue]")
                    return

                profiles = registry.list_profiles(profile_type)
                self._display_profile_list(profile_type, profiles)
            else:
                # List all profile types with summary
                summary = registry.get_profile_summary()
                self.console.print(
                    f"[green]Profile System Summary: {summary['total']} profiles total[/green]"
                )

                for ptype in registry.get_profile_types():
                    profiles = registry.list_profiles(ptype)
                    self._display_profile_list(ptype, profiles)

        except Exception as e:
            self.handle_exception(e, "profile listing")

    def show_profile_details(self, profile_name: str):
        """Show detailed information about a specific profile."""
        try:
            # Find the profile across all types
            result = registry.find_profile(profile_name)
            profile = result["profile"]
            profile_type = result["type"]

            self.console.print(f"[green]Profile: {profile_name}[/green]")
            self.console.print(f"[blue]Type: {profile_type}[/blue]")

            # Convert to JSON-serializable format
            profile_data = registry.to_json_serializable(profile)
            self.console.print_json(data=profile_data)

        except ValueError:
            self.console.print(f"[red]Profile not found: {profile_name}[/red]")
            self.console.print(
                "[blue]Use 'czbillgen profiles list' to see available profiles[/blue]"
            )
        except Exception as e:
            self.handle_exception(e, "profile details")

    def validate_profile_configuration(self, profile_name: str, profile_type: str):
        """Validate a profile configuration for pipeline usage."""
        try:
            from profiles import validate_profile_exists

            if validate_profile_exists(profile_name, profile_type):
                self.console.print(
                    f"[green]✅ Profile '{profile_name}' is valid for {profile_type} usage[/green]"
                )

                # Get and display the profile
                profile = registry.get_profile(profile_type, profile_name)
                profile_data = registry.to_json_serializable(profile)

                self.console.print("[blue]Profile configuration:[/blue]")
                self.console.print_json(data=profile_data)
            else:
                self.console.print(
                    f"[red]❌ Profile '{profile_name}' is not valid for {profile_type} usage[/red]"
                )

        except Exception as e:
            self.handle_exception(e, "profile validation")

    def _display_profile_list(self, profile_type: str, profiles: list):
        """Display a list of profiles for a given type."""
        if not profiles:
            self.console.print(f"[yellow]No {profile_type} profiles found[/yellow]")
            return

        data = [{"name": profile} for profile in profiles]

        display_summary_table(
            self.console,
            f"{profile_type.title()} Profiles ({len(profiles)})",
            data,
            ["name"],
        )


# Create Typer app
app = typer.Typer(help="List and manage profiles for metadata, variance, and anomaly")
list_cmd = ProfileListCommand()


@app.command()
def all(
    profile_type: Optional[str] = typer.Option(
        None,
        "--type",
        "-t",
        help="Filter by profile type (metadata, variance, anomaly)",
    ),
):
    """List all available profiles."""
    list_cmd.list_all_profiles(profile_type)


@app.command()
def metadata():
    """List all metadata profiles."""
    list_cmd.list_all_profiles("metadata")


@app.command()
def variance():
    """List all variance profiles."""
    list_cmd.list_all_profiles("variance")


@app.command()
def anomaly():
    """List all anomaly profiles."""
    list_cmd.list_all_profiles("anomaly")


@app.command()
def show(
    profile_name: str = typer.Argument(..., help="Profile name to show details for"),
):
    """Show detailed information about a specific profile."""
    list_cmd.show_profile_details(profile_name)


@app.command()
def validate(
    profile_name: str = typer.Argument(..., help="Profile name to validate"),
    profile_type: str = typer.Argument(..., help="Profile type (variance, anomaly)"),
):
    """Validate a profile configuration for pipeline usage."""
    list_cmd.validate_profile_configuration(profile_name, profile_type)


@app.command()
def types():
    """List all available profile types."""
    profile_types = registry.get_profile_types()
    summary = registry.get_profile_summary()

    data = []
    for ptype in profile_types:
        count = summary.get(ptype, 0)
        data.append({"type": ptype, "count": count})

    list_cmd.console.print(
        f"[green]Profile System: {summary['total']} total profiles[/green]"
    )
    display_summary_table(list_cmd.console, "Profile Types", data, ["type", "count"])
