"""Syntax highlighting using Pygments with ANSI color depth awareness."""

from pygments import highlight as pygments_highlight
from pygments.formatters.terminal import TerminalFormatter
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound


def highlight(
    code: str,
    language: str = "python",
    color_depth: str = "16",
    line_numbers: bool = False,
) -> str:
    """Highlight code with syntax coloring appropriate for client's terminal.

    Args:
        code: Source code to highlight
        language: Language name (python, toml, etc.)
        color_depth: Client color capability ("truecolor", "256", or "16")
        line_numbers: Whether to prefix lines with line numbers

    Returns:
        ANSI-colored code string, or original code if language is unknown.
        Trailing newlines are stripped for clean telnet display.
    """
    if not code:
        return ""

    # Try to get the appropriate lexer
    try:
        lexer = get_lexer_by_name(language)
    except ClassNotFound:
        # Unknown language, return original text
        return code

    # Choose formatter based on color depth
    # Use 256-color formatter for both "256" and "truecolor"
    # Pygments doesn't have a true truecolor formatter, 256 is the best we have
    formatter = TerminalFormatter() if color_depth == "16" else Terminal256Formatter()

    # Apply syntax highlighting
    result = pygments_highlight(code, lexer, formatter)

    # Strip trailing newline that Pygments adds
    if result.endswith("\n"):
        result = result[:-1]

    # Add line numbers if requested
    if line_numbers:
        result = _add_line_numbers(result)

    return result


def _add_line_numbers(highlighted_code: str) -> str:
    """Add line numbers to highlighted code using ANSI dim styling.

    Args:
        highlighted_code: ANSI-colored code string

    Returns:
        Code with line numbers prefixed to each line
    """
    lines = highlighted_code.split("\n")
    numbered_lines = []

    # ANSI dim styling for line numbers
    dim = "\033[2m"
    reset = "\033[0m"

    for i, line in enumerate(lines, start=1):
        # Format: dim line number, reset, then the code
        numbered_line = f"{dim}{i:3d}{reset} {line}"
        numbered_lines.append(numbered_line)

    return "\n".join(numbered_lines)
