"""Hanzo Observability - Metrics, logs, traces CLI.

Full visibility into your systems.
"""

import click
from rich import box
from rich.table import Table
from rich.panel import Panel

from ..utils.output import console


@click.group(name="o11y")
def o11y_group():
    """Hanzo Observability - Metrics, logs, and traces.

    \b
    Metrics:
      hanzo o11y metrics list      # List metric series
      hanzo o11y metrics query     # Query metrics (PromQL)

    \b
    Logs:
      hanzo o11y logs search       # Search logs
      hanzo o11y logs tail         # Tail live logs

    \b
    Traces:
      hanzo o11y traces list       # List traces
      hanzo o11y traces show       # Show trace details

    \b
    Dashboards:
      hanzo o11y dashboards list   # List dashboards
      hanzo o11y dashboards create # Create dashboard

    \b
    Alerts:
      hanzo o11y alerts list       # List alert rules
      hanzo o11y alerts create     # Create alert rule
    """
    pass


# ============================================================================
# Metrics
# ============================================================================

@o11y_group.group()
def metrics():
    """Manage metrics and time-series data."""
    pass


@metrics.command(name="list")
@click.option("--filter", "-f", help="Filter metric names")
def metrics_list(filter: str):
    """List available metric series."""
    table = Table(title="Metrics", box=box.ROUNDED)
    table.add_column("Name", style="cyan")
    table.add_column("Type", style="white")
    table.add_column("Labels", style="dim")
    table.add_column("Points", style="dim")

    series = [
        ("http_requests_total", "counter", "method, status, path", "1.2M"),
        ("http_request_duration_seconds", "histogram", "method, path", "856K"),
        ("process_cpu_seconds_total", "counter", "instance", "245K"),
        ("process_memory_bytes", "gauge", "instance", "245K"),
    ]

    for name, mtype, labels, points in series:
        if filter and filter not in name:
            continue
        table.add_row(name, mtype, labels, points)

    console.print(table)


@metrics.command(name="query")
@click.argument("promql")
@click.option("--start", "-s", help="Start time")
@click.option("--end", "-e", help="End time")
@click.option("--step", default="1m", help="Query step")
def metrics_query(promql: str, start: str, end: str, step: str):
    """Query metrics using PromQL."""
    console.print(f"[cyan]Query:[/cyan] {promql}")
    console.print(f"[cyan]Step:[/cyan] {step}")
    console.print()
    console.print("[dim]No data points returned[/dim]")


@metrics.command(name="export")
@click.argument("promql")
@click.option("--format", "-f", type=click.Choice(["json", "csv"]), default="json")
@click.option("--output", "-o", help="Output file")
def metrics_export(promql: str, format: str, output: str):
    """Export metrics to file."""
    console.print(f"[green]✓[/green] Exported to {output or 'stdout'}")


# ============================================================================
# Logs
# ============================================================================

@o11y_group.group()
def logs():
    """Search and analyze logs."""
    pass


@logs.command(name="search")
@click.argument("query")
@click.option("--source", "-s", help="Log source")
@click.option("--level", "-l", type=click.Choice(["debug", "info", "warn", "error"]))
@click.option("--limit", "-n", default=100, help="Max results")
def logs_search(query: str, source: str, level: str, limit: int):
    """Search logs."""
    console.print(f"[cyan]Query:[/cyan] {query}")
    if source:
        console.print(f"[cyan]Source:[/cyan] {source}")
    if level:
        console.print(f"[cyan]Level:[/cyan] {level}")
    console.print()
    console.print("[dim]No matching logs found[/dim]")


@logs.command(name="tail")
@click.option("--source", "-s", help="Log source")
@click.option("--filter", "-f", help="Filter expression")
def logs_tail(source: str, filter: str):
    """Tail live logs."""
    console.print("[cyan]Tailing logs...[/cyan]")
    console.print("Press Ctrl+C to stop")


@logs.command(name="sources")
def logs_sources():
    """List log sources."""
    table = Table(title="Log Sources", box=box.ROUNDED)
    table.add_column("Source", style="cyan")
    table.add_column("Type", style="white")
    table.add_column("Status", style="green")
    table.add_column("Volume", style="dim")

    console.print(table)


# ============================================================================
# Traces
# ============================================================================

@o11y_group.group()
def traces():
    """Analyze distributed traces."""
    pass


@traces.command(name="list")
@click.option("--service", "-s", help="Filter by service")
@click.option("--operation", "-o", help="Filter by operation")
@click.option("--min-duration", help="Minimum duration (e.g., 100ms)")
@click.option("--limit", "-n", default=20, help="Max traces")
def traces_list(service: str, operation: str, min_duration: str, limit: int):
    """List recent traces."""
    table = Table(title="Traces", box=box.ROUNDED)
    table.add_column("Trace ID", style="cyan")
    table.add_column("Service", style="white")
    table.add_column("Operation", style="white")
    table.add_column("Duration", style="yellow")
    table.add_column("Spans", style="dim")
    table.add_column("Status", style="green")

    console.print(table)


@traces.command(name="show")
@click.argument("trace_id")
def traces_show(trace_id: str):
    """Show trace details."""
    console.print(Panel(
        f"[cyan]Trace ID:[/cyan] {trace_id}\n"
        f"[cyan]Duration:[/cyan] 245ms\n"
        f"[cyan]Spans:[/cyan] 12\n"
        f"[cyan]Services:[/cyan] api, auth, database",
        title="Trace Details",
        border_style="cyan"
    ))


@traces.command(name="services")
def traces_services():
    """List traced services."""
    table = Table(title="Services", box=box.ROUNDED)
    table.add_column("Service", style="cyan")
    table.add_column("Operations", style="white")
    table.add_column("Avg Duration", style="yellow")
    table.add_column("Error Rate", style="red")

    console.print(table)


# ============================================================================
# Dashboards
# ============================================================================

@o11y_group.group()
def dashboards():
    """Manage observability dashboards."""
    pass


@dashboards.command(name="list")
def dashboards_list():
    """List all dashboards."""
    table = Table(title="Dashboards", box=box.ROUNDED)
    table.add_column("Name", style="cyan")
    table.add_column("Panels", style="white")
    table.add_column("Updated", style="dim")

    console.print(table)


@dashboards.command(name="create")
@click.option("--name", "-n", prompt=True, help="Dashboard name")
@click.option("--file", "-f", help="Import from JSON file")
def dashboards_create(name: str, file: str):
    """Create a new dashboard."""
    console.print(f"[green]✓[/green] Dashboard '{name}' created")
    console.print(f"[dim]View at: https://dashboards.hanzo.ai/{name}[/dim]")


@dashboards.command(name="open")
@click.argument("name")
def dashboards_open(name: str):
    """Open dashboard in browser."""
    import webbrowser
    url = f"https://dashboards.hanzo.ai/{name}"
    console.print(f"[cyan]Opening: {url}[/cyan]")
    webbrowser.open(url)


# ============================================================================
# Alerts
# ============================================================================

@o11y_group.group()
def alerts():
    """Manage alert rules."""
    pass


@alerts.command(name="list")
@click.option("--status", type=click.Choice(["firing", "pending", "inactive", "all"]), default="all")
def alerts_list(status: str):
    """List alert rules."""
    table = Table(title="Alert Rules", box=box.ROUNDED)
    table.add_column("Name", style="cyan")
    table.add_column("Condition", style="white")
    table.add_column("Status", style="green")
    table.add_column("Severity", style="yellow")
    table.add_column("Last Fired", style="dim")

    console.print(table)


@alerts.command(name="create")
@click.option("--name", "-n", prompt=True, help="Alert name")
@click.option("--condition", "-c", required=True, help="PromQL condition")
@click.option("--severity", "-s", type=click.Choice(["critical", "warning", "info"]), default="warning")
@click.option("--channel", help="Notification channel")
def alerts_create(name: str, condition: str, severity: str, channel: str):
    """Create an alert rule."""
    console.print(f"[green]✓[/green] Alert rule '{name}' created")


@alerts.command(name="silence")
@click.argument("alert_name")
@click.option("--duration", "-d", default="1h", help="Silence duration")
def alerts_silence(alert_name: str, duration: str):
    """Silence an alert."""
    console.print(f"[green]✓[/green] Alert '{alert_name}' silenced for {duration}")


@alerts.command(name="delete")
@click.argument("alert_name")
def alerts_delete(alert_name: str):
    """Delete an alert rule."""
    console.print(f"[green]✓[/green] Alert rule '{alert_name}' deleted")
