"""Structured log formatter for the dev server."""

from __future__ import annotations

from datetime import datetime

from rich.markup import escape

from hatchdx.utils.console import console


def log_server_start(command: str) -> None:
    """Log that the server process is starting."""
    _log("START", f"Starting server: {command}", style="bold green")


def log_server_stop() -> None:
    """Log that the server process is stopping."""
    _log("STOP", "Server stopped", style="bold yellow")


def log_server_restart(changed_path: str) -> None:
    """Log that a file change triggered a restart."""
    _log("RELOAD", f"File changed: {changed_path}", style="bold cyan")


def log_server_ready(tools: list[str]) -> None:
    """Log that the server is initialized and ready."""
    tool_count = len(tools)
    label = "tool" if tool_count == 1 else "tools"
    _log("READY", f"Server ready ({tool_count} {label})", style="bold green")


def log_server_error(message: str) -> None:
    """Log a server error."""
    _log("ERROR", message, style="bold red")


def log_tool_call(tool_name: str, arguments: dict) -> None:
    """Log an outgoing tool call."""
    import json

    args_str = json.dumps(arguments) if arguments else "{}"
    _log("CALL", f"{tool_name}({args_str})", style="bold magenta")


def log_tool_result(tool_name: str, latency_ms: float, *, is_error: bool = False) -> None:
    """Log a tool call result with latency."""
    status = "[red]error[/]" if is_error else "[green]ok[/]"
    _log("RESULT", f"{tool_name} → {status} ({latency_ms:.0f}ms)", style="bold magenta")


def _log(tag: str, message: str, *, style: str = "bold") -> None:
    """Print a structured log line with timestamp and tag."""
    timestamp = datetime.now().strftime("%H:%M:%S")
    console.print(
        f"[dim]{timestamp}[/] [{style}]{tag:>7}[/] {escape(message)}"
    )
