"""Rich-formatted test result reporter."""

from __future__ import annotations

import json

from rich.table import Table

from hatchdx.harness.models import TestResult
from hatchdx.utils.console import console


def report_results(
    results: list[TestResult],
    *,
    server_name: str,
    verbose: bool = False,
) -> int:
    """Print test results and return exit code (0 = all passed, 1 = failures)."""
    passed_count = sum(1 for r in results if r.passed)
    failed_count = len(results) - passed_count
    total_ms = sum(r.latency_ms for r in results)

    # Verbose: show full request/response per test
    if verbose:
        for result in results:
            _print_verbose_result(result)
        console.print()

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

    for result in results:
        status = "[green]✓[/]" if result.passed else "[red]✗[/]"
        latency = f"{result.latency_ms:.0f}ms"
        details = result.failure_reason or ""
        # Truncate long failure reasons for the table
        if len(details) > 60:
            details = details[:57] + "..."
        table.add_row(result.test_case.name, status, latency, details)

    console.print(table)
    console.print()

    # Summary footer
    if failed_count == 0:
        console.print(
            f"[bold green]Results: {passed_count} passed[/] ({total_ms:.0f}ms total)"
        )
    else:
        console.print(
            f"[bold red]Results: {passed_count} passed, {failed_count} failed[/] "
            f"({total_ms:.0f}ms total)"
        )

    return 0 if failed_count == 0 else 1


def _print_verbose_result(result: TestResult) -> None:
    """Print detailed request/response for a single test."""
    status_icon = "[green]✓[/]" if result.passed else "[red]✗[/]"
    console.print(f"\n  {status_icon} [bold]{result.test_case.name}[/]")

    # Request
    request_data = {
        "tool": result.test_case.tool,
        "arguments": result.test_case.input,
    }
    console.print(f"  [dim]Request:[/]  {json.dumps(request_data)}")

    # Response
    if result.actual_response:
        console.print(f"  [dim]Response:[/] {json.dumps(result.actual_response)}")

    # Failure reason
    if result.failure_reason:
        console.print(f"  [dim]Failure:[/]  [red]{result.failure_reason}[/]")
