from typer import Typer, Option
from typing import Optional
from pathlib import Path
from rich.panel import Panel
from rich.align import Align
from .logo import LOGO
from .console import console
from .io import (
    print_success,
    print_info,
    create_chain_tree,
    display_yaml_config,
)

app = Typer(help="PrimeFeat: Primordial Feature Detection & Characterization")


@app.command()
def main() -> None:
    """Display PrimeFeat logo and welcome message."""
    console.print(
        Panel(
            Align.center(LOGO),
            # title="[bold magenta]PrimeFeat[/bold magenta]",
            subtitle="Primordial Feature Detection & Characterization",
            border_style="cyan",
        )
    )
    console.print("\n[cyan]Available commands:[/cyan]")
    console.print("  • [yellow]primefeat info[/yellow]      - Show package information")
    console.print("  • [yellow]primefeat chains[/yellow]    - Inspect MCMC chains")
    console.print("  • [yellow]primefeat cache[/yellow]     - Manage computation cache")
    console.print("\nFor help on any command: [dim]primefeat <command> --help[/dim]\n")


@app.command()
def info() -> None:
    """Display package information and dependencies."""
    try:
        from importlib.metadata import version, metadata

        pkg_version = version("primefeat")
        pkg_metadata = metadata("primefeat")
    except Exception:
        pkg_version = "unknown"
        pkg_metadata = None

    from rich.table import Table

    # Version info
    info_table = Table(title="PrimeFeat Package Information", show_header=False)
    info_table.add_column("Property", style="cyan")
    info_table.add_column("Value", style="yellow")

    info_table.add_row("Version", pkg_version)
    info_table.add_row("Python", f">= 3.10")

    console.print(info_table)

    # Dependencies
    deps_table = Table(title="Core Dependencies", show_header=True)
    deps_table.add_column("Package", style="cyan")
    deps_table.add_column("Purpose", style="dim")

    deps_table.add_row("getdist", "MCMC chain analysis")
    deps_table.add_row("matplotlib", "Plotting and visualization")
    deps_table.add_row("numpy", "Numerical computations")
    deps_table.add_row("scipy", "Scientific computing")
    deps_table.add_row("scikit-learn", "PCA and statistical tools")
    deps_table.add_row("rich", "Enhanced CLI output")
    deps_table.add_row("typer", "CLI framework")

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

    # Optional dependencies
    opt_table = Table(title="Optional Dependencies", show_header=True)
    opt_table.add_column("Package", style="cyan")
    opt_table.add_column("Purpose", style="dim")
    opt_table.add_column("Installed", justify="center")

    try:
        import numba

        numba_installed = "[green]✓[/green]"
    except ImportError:
        numba_installed = "[dim]✗[/dim]"

    try:
        import pywt

        pywt_installed = "[green]✓[/green]"
    except ImportError:
        pywt_installed = "[dim]✗[/dim]"

    try:
        import marimo

        marimo_installed = "[green]✓[/green]"
    except ImportError:
        marimo_installed = "[dim]✗[/dim]"

    opt_table.add_row("numba", "JIT compilation (faster)", numba_installed)
    opt_table.add_row("pywavelets", "Wavelet analysis", pywt_installed)
    opt_table.add_row("marimo", "Interactive notebooks", marimo_installed)

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


@app.command()
def chains(
    yaml_path: Path = Option(..., "--yaml", "-y", help="Path to chains YAML config"),
    show_config: bool = Option(
        False, "--show-config", "-c", help="Display YAML configuration"
    ),
) -> None:
    """Inspect MCMC chains from YAML configuration."""
    if not yaml_path.exists():
        from .io import print_error

        print_error(f"YAML file not found: {yaml_path}")
        raise SystemExit(1)

    if show_config:
        display_yaml_config(yaml_path)

    try:
        from .load import load_chains
        import yaml

        with open(yaml_path) as f:
            config = yaml.safe_load(f)

        if "chains" in config:
            # Display chain structure
            for subset_name, chains_dict in config["chains"].items():
                tree = create_chain_tree(chains_dict, subset_name)
                console.print(tree)

        print_success(f"Loaded chains from {yaml_path.name}")

    except Exception as e:
        from .io import print_error

        print_error(f"Failed to load chains", details=str(e))
        raise SystemExit(1)


@app.command()
def cache(
    action: str = Option("info", help="Action: info, clear, or stats"),
) -> None:
    """Manage computation cache."""
    from rich.table import Table

    if action == "clear":
        from .compute import clear_Pk_cache
        from rich.prompt import Confirm

        if Confirm.ask("[yellow]Clear computation cache?[/yellow]"):
            clear_Pk_cache()
            print_success("Cache cleared")
        else:
            print_info("Cache clear cancelled")

    elif action == "info" or action == "stats":
        from .compute import get_Pk_cache_info

        try:
            cache_info = get_Pk_cache_info()

            cache_table = Table(title="Cache Statistics", show_header=False)
            cache_table.add_column("Metric", style="cyan")
            cache_table.add_column("Value", style="yellow", justify="right")

            cache_table.add_row("Cache hits", f"{cache_info['hits']:,}")
            cache_table.add_row("Cache misses", f"{cache_info['misses']:,}")
            cache_table.add_row("Hit rate", f"{cache_info['hit_rate']:.1%}")
            cache_table.add_row("Cached entries", f"{cache_info['size']:,}")

            console.print(cache_table)
        except Exception as e:
            print_info(f"Cache info unavailable: {e}")

    else:
        from .io import print_error

        print_error(f"Unknown action: {action}", details="Use: info, clear, or stats")


if __name__ == "__main__":
    app()
