"""Rich formatting utilities for agent output.

Provides beautiful terminal output for debugging sessions.
"""

from __future__ import annotations

from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.syntax import Syntax
from rich.table import Table

console = Console()


def print_error_summary(error: dict) -> None:
    """Print a summary panel for an error.

    Args:
        error: Error dictionary from Hikaflow API.
    """
    exception_type = error.get("exception_type", "Error")
    message = error.get("message", "No message")
    error_id = error.get("id", "unknown")
    count = error.get("count", 0)
    file_loc = error.get("file", "unknown")
    line = error.get("line", "?")

    panel = Panel(
        f"[bold red]{exception_type}[/]\n\n"
        f"{message}\n\n"
        f"[dim]Location: {file_loc}:{line}[/]\n"
        f"[dim]Occurrences: {count}[/]",
        title=f"Error: {error_id}",
        border_style="red",
    )
    console.print(panel)


def print_errors_table(errors: list[dict]) -> None:
    """Print errors as a Rich table.

    Args:
        errors: List of error dictionaries.
    """
    if not errors:
        console.print("[yellow]No errors found.[/]")
        return

    table = Table(title="Production Errors", show_header=True, header_style="bold green")
    table.add_column("ID", style="dim")
    table.add_column("Type", style="red")
    table.add_column("Message")
    table.add_column("Count", justify="right")
    table.add_column("Last Seen", style="dim")

    for e in errors:
        msg = e.get("message", "")[:40]
        if len(e.get("message", "")) > 40:
            msg += "..."

        table.add_row(
            e.get("id", "N/A"),
            e.get("exception_type", "Error"),
            msg,
            str(e.get("count", 0)),
            e.get("last_seen", "N/A"),
        )

    console.print(table)


def print_stack_trace(stack_trace: str) -> None:
    """Print a formatted stack trace.

    Args:
        stack_trace: Raw stack trace string.
    """
    syntax = Syntax(stack_trace, "python", theme="monokai", line_numbers=True)
    panel = Panel(syntax, title="Stack Trace", border_style="red")
    console.print(panel)


def print_diff(diff: str, title: str = "Changes") -> None:
    """Print a syntax-highlighted diff.

    Args:
        diff: Unified diff content.
        title: Panel title.
    """
    syntax = Syntax(diff, "diff", theme="monokai", line_numbers=False)
    panel = Panel(syntax, title=title, border_style="green")
    console.print(panel)


def print_transcript(transcript: dict) -> None:
    """Print I/O transcript details.

    Args:
        transcript: Transcript dictionary with http, sql, time keys.
    """
    # HTTP calls
    if transcript.get("http"):
        http_table = Table(title="HTTP Calls", show_header=True)
        http_table.add_column("Method")
        http_table.add_column("URL")
        http_table.add_column("Status", justify="right")

        for item in transcript["http"]:
            status = str(item.get("status", "?"))
            status_style = "green" if status.startswith("2") else "red"
            http_table.add_row(
                item.get("method", "GET"),
                item.get("url", "unknown")[:50],
                f"[{status_style}]{status}[/]",
            )
        console.print(http_table)
        console.print()

    # SQL queries
    if transcript.get("sql"):
        sql_table = Table(title="SQL Queries", show_header=True)
        sql_table.add_column("Query")
        sql_table.add_column("Rows", justify="right")

        for item in transcript["sql"]:
            query = item.get("query", "")[:60]
            if len(item.get("query", "")) > 60:
                query += "..."
            sql_table.add_row(query, str(item.get("row_count", "?")))
        console.print(sql_table)
        console.print()

    # Time values
    if transcript.get("time"):
        time_table = Table(title="Time Values", show_header=True)
        time_table.add_column("Function")
        time_table.add_column("Value")

        for item in transcript["time"]:
            time_table.add_row(
                item.get("function", "time"),
                str(item.get("value", "N/A")),
            )
        console.print(time_table)


def print_replay_results(results: list[dict]) -> None:
    """Print replay run results.

    Args:
        results: List of replay result dictionaries.
    """
    passed = sum(1 for r in results if r.get("reproduced"))
    total = len(results)

    if passed == total:
        panel = Panel(
            f"[bold green]{passed}/{total} runs reproduced the error[/]\n\n"
            "The error was consistently reproduced. Ready to debug.",
            title="Replay Successful",
            border_style="green",
        )
    else:
        panel = Panel(
            f"[bold yellow]{passed}/{total} runs reproduced the error[/]\n\n"
            "Warning: Error did not reproduce consistently.\n"
            "This may indicate timing-dependent behavior.",
            title="Replay Inconsistent",
            border_style="yellow",
        )

    console.print(panel)


def print_hypotheses(hypotheses: list[dict]) -> None:
    """Print fix hypotheses.

    Args:
        hypotheses: List of hypothesis dictionaries.
    """
    if not hypotheses:
        console.print("[yellow]No fix hypotheses generated.[/]")
        return

    console.print("\n[bold]Fix Hypotheses:[/]\n")

    for i, h in enumerate(hypotheses, 1):
        confidence = h.get("confidence", 0)
        confidence_style = "green" if confidence > 0.7 else "yellow" if confidence > 0.4 else "red"

        console.print(f"[bold]{i}. {h.get('strategy', 'Fix')}[/] ", end="")
        console.print(f"[{confidence_style}](confidence: {confidence:.0%})[/]")
        console.print(f"   [dim]Root cause:[/] {h.get('root_cause', 'Unknown')}")

        if h.get("diff"):
            console.print()
            print_diff(h["diff"], title=f"Hypothesis {i}")

        console.print()


def print_validation_result(result: dict) -> None:
    """Print fix validation result.

    Args:
        result: Validation result dictionary.
    """
    verdict = result.get("verdict", "UNKNOWN")
    passed = result.get("passed", 0)
    total = result.get("total", 0)
    cert_id = result.get("certificate_id", "N/A")

    if verdict == "PROVEN_FIX":
        panel = Panel(
            f"[bold green]PROVEN FIX[/]\n\n"
            f"Runs passed: {passed}/{total}\n"
            f"Certificate ID: {cert_id}\n\n"
            "The fix has been mathematically proven to resolve the error!",
            title="Validation Result",
            border_style="green",
        )
    elif verdict == "FLAKY_FIX":
        panel = Panel(
            f"[bold yellow]FLAKY FIX[/]\n\n"
            f"Runs passed: {passed}/{total}\n\n"
            "The fix works sometimes but not consistently.",
            title="Validation Result",
            border_style="yellow",
        )
    else:
        panel = Panel(
            f"[bold red]{verdict}[/]\n\n"
            f"Runs passed: {passed}/{total}\n\n"
            "The fix did not resolve the error.",
            title="Validation Result",
            border_style="red",
        )

    console.print(panel)


def print_similar_fixes(matches: list[dict]) -> None:
    """Print similar past fixes.

    Args:
        matches: List of similar fix matches.
    """
    if not matches:
        console.print("[dim]No similar fixes found in the pattern database.[/]")
        return

    table = Table(title="Similar Past Fixes", show_header=True)
    table.add_column("Error Type")
    table.add_column("Fix Type")
    table.add_column("Success Rate", justify="right")

    for m in matches:
        success = m.get("success_rate", 0)
        success_style = "green" if success > 0.8 else "yellow" if success > 0.5 else "red"
        table.add_row(
            m.get("exception_type", "Error"),
            m.get("fix_type", "fix"),
            f"[{success_style}]{success:.0%}[/]",
        )

    console.print(table)


def print_agent_thinking(message: str) -> None:
    """Print agent thinking/status message.

    Args:
        message: Status message to display.
    """
    console.print(f"[dim italic]{message}[/]")


def print_agent_response(response: str) -> None:
    """Print agent response with markdown formatting.

    Args:
        response: Markdown-formatted response text.
    """
    md = Markdown(response)
    console.print(md)


def print_welcome() -> None:
    """Print welcome message for interactive mode."""
    panel = Panel(
        "[bold green]Hikaflow[/] - AI-powered production error debugger\n\n"
        "Commands:\n"
        "  [green]errors[/]   - List recent production errors\n"
        "  [green]debug[/]    - Start debugging session\n"
        "  [green]watch[/]    - Watch for new errors\n"
        "  [green]status[/]   - Show project status\n"
        "  [green]help[/]     - Show all commands\n"
        "  [green]exit[/]     - Exit interactive mode\n\n"
        "Or just ask a question in natural language.",
        title="Interactive Mode",
        border_style="green",
    )
    console.print(panel)


def print_goodbye() -> None:
    """Print goodbye message."""
    console.print("\n[dim]Goodbye![/]\n")


def format_tool_call(name: str, args: dict) -> str:
    """Format a tool call for display.

    Args:
        name: Tool name.
        args: Tool arguments.

    Returns:
        Formatted string.
    """
    args_str = ", ".join(f"{k}={v!r}" for k, v in args.items())
    return f"[dim]Calling {name}({args_str})[/]"
