"""Rich build summary display for deploy command."""

from __future__ import annotations

from typing import Any

from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from hud.utils.hud_console import HUDConsole


def display_build_summary(
    status_response: dict[str, Any],
    registry_id: str,
    console: HUDConsole | None = None,
    platform_url: str | None = None,
    env_name: str | None = None,
) -> None:
    """Display a rich summary of a completed build.

    Args:
        status_response: Response from /builds/{id}/status endpoint
        registry_id: Registry/environment ID
        console: Optional HUDConsole for output
        platform_url: Base URL for HUD platform
        env_name: Environment display name
    """
    if console is None:
        console = HUDConsole()

    if platform_url is None:
        from hud.settings import settings

        platform_url = settings.hud_web_url

    rich_console = Console()

    status = status_response.get("status", "UNKNOWN")
    version = status_response.get("version", "unknown")
    duration = status_response.get("duration_seconds")
    image_name = status_response.get("image_name")
    uri = status_response.get("uri")
    lock_data = status_response.get("lock")

    # Format duration
    duration_str = _format_duration(duration) if duration else "unknown"

    # Build status line with checkmark/cross
    if status == "SUCCEEDED":
        status_icon = "[green]✓[/green]"
        status_text = f"{status_icon} [bold green]{status}[/bold green]"
    elif status == "FAILED":
        status_icon = "[red]✗[/red]"
        status_text = f"{status_icon} [bold red]{status}[/bold red]"
    else:
        status_icon = "[yellow]●[/yellow]"
        status_text = f"{status_icon} [bold yellow]{status}[/bold yellow]"

    # Create summary table
    summary_lines = [
        f"[bold]Status:[/bold]     {status_text}",
        f"[bold]Duration:[/bold]   {duration_str}",
        f"[bold]Version:[/bold]    {version}",
    ]

    if env_name:
        summary_lines.insert(0, f"[bold]Environment:[/bold] [cyan]{env_name}[/cyan]")

    if uri:
        summary_lines.append(f"[bold]Image:[/bold]      [dim]{uri}[/dim]")
    elif image_name:
        summary_lines.append(f"[bold]Image:[/bold]      [dim]{image_name}[/dim]")

    summary_content = "\n".join(summary_lines)

    # Print main summary panel
    rich_console.print()
    rich_console.print(
        Panel(
            summary_content,
            title="[bold cyan]Build Summary[/bold cyan]",
            border_style="cyan",
            padding=(1, 2),
        )
    )

    # Parse and display lock data if available
    if lock_data and isinstance(lock_data, dict):
        _display_lock_details(rich_console, lock_data)

    # Print platform link
    env_url = f"{platform_url}/environments/{registry_id}"
    rich_console.print()
    rich_console.print(
        Panel(
            f"[bold]View on HUD:[/bold] [link={env_url}]{env_url}[/link]",
            border_style="blue",
            padding=(0, 2),
        )
    )

    # Show usage example for successful builds
    if status == "SUCCEEDED" and env_name and lock_data:
        _display_usage_example(rich_console, env_name, lock_data)

    rich_console.print()


def _display_lock_details(
    rich_console: Console,
    lock_data: dict[str, Any],
) -> None:
    """Display details from the lock file.

    Args:
        rich_console: Rich Console for output
        lock_data: Parsed lock file data
    """
    tasks = lock_data.get("tasks") or []
    if tasks:
        rich_console.print()
        tasks_table = Table(
            title=f"[bold]Tasks ({len(tasks)})[/bold]",
            show_header=True,
            header_style="bold",
            border_style="dim",
        )
        tasks_table.add_column("Slug", style="cyan")
        tasks_table.add_column("Task", style="magenta")
        tasks_table.add_column("Args", style="dim")

        for task in tasks[:10]:
            if not isinstance(task, dict):
                tasks_table.add_row(str(task), "", "")
                continue
            slug = str(task.get("slug") or "")
            task_id = str(task.get("task") or task.get("id") or "")
            args = task.get("args") or {}
            args_str = ", ".join(sorted(args)) if isinstance(args, dict) and args else "No args"
            tasks_table.add_row(slug, task_id, args_str)

        if len(tasks) > 10:
            tasks_table.add_row(
                f"[dim]... and {len(tasks) - 10} more[/dim]",
                "",
                "",
            )

        rich_console.print(tasks_table)

    # Display environment variables
    env_config = lock_data.get("environment") or {}
    if env_config:
        variables = env_config.get("variables") or {}
        required_vars = variables.get("required", [])
        optional_vars = variables.get("optional", [])

        if required_vars or optional_vars:
            rich_console.print()
            env_lines = []
            if required_vars:
                env_lines.append(f"[bold]Required:[/bold] {', '.join(required_vars)}")
            if optional_vars:
                env_lines.append(f"[bold]Optional:[/bold] {', '.join(optional_vars)}")

            rich_console.print(
                Panel(
                    "\n".join(env_lines),
                    title="[bold]Environment Variables[/bold]",
                    border_style="dim",
                    padding=(0, 2),
                )
            )

    capabilities = lock_data.get("capabilities") or []
    if capabilities:
        capability_names = [
            capability.get("name", str(capability))
            if isinstance(capability, dict)
            else str(capability)
            for capability in capabilities[:10]
        ]
        capabilities_str = ", ".join(capability_names)
        if len(capabilities) > 10:
            capabilities_str += f", ... and {len(capabilities) - 10} more"

        rich_console.print()
        rich_console.print(
            Panel(
                f"[bold]Capabilities ({len(capabilities)}):[/bold] {capabilities_str}",
                border_style="dim",
                padding=(0, 2),
            )
        )


def _display_usage_example(
    rich_console: Console,
    env_name: str,
    lock_data: dict[str, Any],
) -> None:
    """Display a task JSON usage example after a successful deploy."""
    import json as json_mod

    tasks = lock_data.get("tasks") or []
    if not tasks:
        return

    first = tasks[0]
    if not isinstance(first, dict):
        return

    task_example: dict[str, Any] = {
        "env": env_name,
        "id": first.get("task") or first.get("id") or "",
    }
    if first.get("slug"):
        task_example["slug"] = first["slug"]
    args = first.get("args")
    if isinstance(args, dict) and args:
        task_example["args"] = args

    example_json = json_mod.dumps(task_example, indent=2)
    rich_console.print()
    rich_console.print(
        Panel(
            f"[bold]Task JSON:[/bold]\n[dim]{example_json}[/dim]",
            title="[bold]Quick Start[/bold]",
            border_style="green",
            padding=(1, 2),
        )
    )


def _format_duration(seconds: float) -> str:
    """Format duration in seconds to human-readable string.

    Args:
        seconds: Duration in seconds

    Returns:
        Human-readable duration (e.g., "2m 15s")
    """
    if seconds < 60:
        return f"{int(seconds)}s"
    elif seconds < 3600:
        minutes = int(seconds // 60)
        secs = int(seconds % 60)
        return f"{minutes}m {secs}s"
    else:
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        return f"{hours}h {minutes}m"


def display_upload_progress(
    uploaded_bytes: int,
    total_bytes: int,
    console: HUDConsole | None = None,
) -> None:
    """Display upload progress.

    Args:
        uploaded_bytes: Bytes uploaded so far
        total_bytes: Total bytes to upload
        console: Optional HUDConsole for output
    """
    if console is None:
        console = HUDConsole()

    from hud.cli.utils.context import format_size

    uploaded_str = format_size(uploaded_bytes)
    total_str = format_size(total_bytes)
    percent = (uploaded_bytes / total_bytes * 100) if total_bytes > 0 else 0

    console.progress_message(f"Uploading: {uploaded_str} / {total_str} ({percent:.1f}%)")
