"""Rich-formatted sandbox execution reporter."""

from __future__ import annotations

from rich.table import Table

from hatchdx.sandbox.models import ContainerStats, SandboxPolicy, SandboxResult
from hatchdx.utils.console import console, error, info, step, success, warning


def report_policy_summary(policy: SandboxPolicy, *, network_enforced: bool = True) -> None:
    """Print a summary of the active sandbox policy."""
    table = Table(
        show_edge=False,
        pad_edge=False,
        title=f"Sandbox Policy: [bold]{policy.name}[/]",
        title_style="bold cyan",
    )
    table.add_column("Setting", style="bold")
    table.add_column("Value")

    # Network
    if not policy.network.enabled:
        net_status = "[red]Disabled[/] (no network access)"
    elif policy.network.allowed_domains:
        domains = ", ".join(policy.network.allowed_domains)
        net_status = f"[yellow]Restricted[/] ({domains})"
    else:
        net_status = "[green]Unrestricted[/]"
    table.add_row("Network", net_status)

    # Enforcement transparency — only shown when domains are restricted but not enforced
    if policy.network.enabled and policy.network.allowed_domains and not network_enforced:
        table.add_row(
            "Enforcement",
            "[yellow]⚠ Domain filtering not yet enforced[/]",
        )
    elif policy.network.enabled and policy.network.allowed_domains and network_enforced:
        table.add_row(
            "Enforcement",
            "[green]✓ Domain filtering active (iptables)[/]",
        )

    # Filesystem
    ro_mounts = ", ".join(policy.filesystem.read_only_mounts) or "[dim]none[/]"
    writable = ", ".join(policy.filesystem.writable_dirs) or "[dim]none[/]"
    table.add_row("Read-only mounts", ro_mounts)
    table.add_row("Writable dirs", writable)

    # Resources
    table.add_row("CPU limit", policy.resources.cpu_limit)
    table.add_row("Memory limit", policy.resources.memory_limit)
    table.add_row("Timeout", f"{policy.resources.timeout_seconds}s")

    console.print(table)
    console.print()


def report_build_status(
    *,
    image_tag: str,
    building: bool = False,
    built: bool = False,
) -> None:
    """Report image build progress."""
    if building:
        step(f"Building image: {image_tag}")
    elif built:
        success(f"Image ready: {image_tag}")


def report_container_status(
    *,
    container_id: str,
    creating: bool = False,
    started: bool = False,
    stopped: bool = False,
) -> None:
    """Report container lifecycle events."""
    short_id = container_id[:12] if container_id else "unknown"
    if creating:
        step(f"Creating container {short_id}")
    elif started:
        success(f"Container started: {short_id}")
    elif stopped:
        info(f"Container stopped: {short_id}")


def report_tool_result(result: SandboxResult) -> None:
    """Print the result of a sandboxed tool call."""
    # Header
    status_icon = "[green]PASS[/]" if not result.is_error else "[red]ERROR[/]"
    console.print(
        f"\n  {status_icon}  [bold]{result.tool_name}[/]"
        f"  [dim]({result.latency_ms:.0f}ms)[/]"
    )

    # Content
    if result.content:
        for item in result.content:
            content_type = item.get("type", "text")
            if content_type == "text":
                text = item.get("text", "")
                # Indent multi-line output
                indented = "\n".join(f"    {line}" for line in text.splitlines())
                if result.is_error:
                    console.print(f"  [dim]Output:[/]\n[red]{indented}[/red]")
                else:
                    console.print(f"  [dim]Output:[/]\n{indented}")
            else:
                console.print(f"  [dim]Output:[/] ({content_type} content)")
    else:
        console.print("  [dim]Output:[/] [dim](empty)[/]")


def report_resource_stats(stats: ContainerStats | None) -> None:
    """Print container resource usage statistics."""
    if stats is None:
        return

    table = Table(show_edge=False, pad_edge=False)
    table.add_column("Metric", style="bold")
    table.add_column("Value", justify="right")

    table.add_row("Memory", f"{stats.memory_usage_mb:.1f} MB")
    table.add_row("Memory %", f"{stats.memory_percent:.1f}%")
    table.add_row("CPU %", f"{stats.cpu_percent:.1f}%")

    console.print()
    console.print(table)


def report_cleanup(*, container_id: str, removed: bool = True) -> None:
    """Report sandbox cleanup."""
    short_id = container_id[:12] if container_id else "unknown"
    if removed:
        success(f"Container {short_id} removed")
    else:
        info(f"Container {short_id} kept (use --keep to preserve containers)")


def report_sandbox_summary(
    results: list[SandboxResult],
    *,
    policy_name: str,
) -> int:
    """Print a summary of all sandbox tool executions.

    Returns an exit code: 0 if no errors, 1 if any tool returned an error.
    """
    if not results:
        warning("No tool calls were executed in the sandbox.")
        return 0

    passed = sum(1 for r in results if not r.is_error)
    failed = len(results) - passed
    total_ms = sum(r.latency_ms for r in results)

    # Results table
    table = Table(show_edge=False, pad_edge=False)
    table.add_column("Tool", style="bold")
    table.add_column("Status", justify="center")
    table.add_column("Latency", justify="right")

    for result in results:
        status = "[green]OK[/]" if not result.is_error else "[red]ERR[/]"
        latency = f"{result.latency_ms:.0f}ms"
        table.add_row(result.tool_name, status, latency)

    console.print()
    console.print(table)
    console.print()

    # Summary
    if failed == 0:
        console.print(
            f"[bold green]Sandbox: {passed} passed[/] "
            f"[dim]({total_ms:.0f}ms total, policy={policy_name})[/]"
        )
    else:
        console.print(
            f"[bold red]Sandbox: {passed} passed, {failed} failed[/] "
            f"[dim]({total_ms:.0f}ms total, policy={policy_name})[/]"
        )

    return 0 if failed == 0 else 1
