"""Shared text formatting helpers used by CLI and MCP server.

This is an internal module (leading underscore). Functions are public
so they can be imported by cli.py and mcp_server.py.
"""

from __future__ import annotations

from typing import Any


def build_source_text(source: dict[str, Any], crash_line: int) -> str:
    """Build a source snippet string with arrow marker on crash line."""
    snippet = source.get("snippet", [])
    lines: list[str] = []
    for entry in snippet:
        lineno = entry.get("lineno", 0)
        code = entry.get("code", "")
        marker = " \u2192 " if lineno == crash_line else "   "
        lines.append(f"{marker}{lineno:>4} | {code}")
    return "\n".join(lines)


def format_local_value(key: str, value: Any, meta: dict[str, Any] | None) -> tuple[str, str, str]:
    """Format a single local variable for display. Returns (name, type_str, value_str)."""
    type_str = ""
    if meta:
        type_str = meta.get("type", "")
        # Shorten qualified types
        if "." in type_str:
            type_str = type_str.rsplit(".", 1)[-1]

    # Format array-like values specially
    if isinstance(value, dict):
        for array_key in ("__array__", "__dataframe__", "__series__"):
            if value.get(array_key):
                dtype = value.get("dtype", "")
                shape = value.get("shape", [])
                shape_str = str(shape)
                extra = f" dtype={dtype}" if dtype else ""
                return key, array_key.strip("_"), f"{shape_str}{extra}"

    value_str = str(value) if not isinstance(value, str) else value
    if len(value_str) > 120:
        value_str = value_str[:117] + "..."
    return key, type_str, value_str


def format_git_head_section(head: Any) -> list[str]:
    """Format git HEAD info as plain text lines."""
    if not isinstance(head, dict):
        return []
    commit = str(head.get("commit") or "?")
    branch = str(head.get("branch") or "?")
    dirty = "true" if bool(head.get("dirty")) else "false"
    detached = "true" if bool(head.get("detached")) else "false"
    return [
        "## Git Head",
        f"commit: {commit}",
        f"branch: {branch}",
        f"dirty: {dirty}",
        f"detached: {detached}",
    ]


def format_crash_file_section(crash_file: Any) -> list[str]:
    """Format crash file blame/location as plain text lines."""
    if not isinstance(crash_file, dict):
        return []
    lines = [
        "",
        "## Crash File",
        f"file_rel: {crash_file.get('file_rel') or '?'!s}",
    ]
    line = crash_file.get("line")
    if line is not None:
        lines.append(f"line: {line}")
    in_repo = "true" if bool(crash_file.get("in_repo")) else "false"
    lines.append(f"in_repo: {in_repo}")
    blame = crash_file.get("blame")
    if isinstance(blame, dict):
        lines.extend(
            (
                "blame:",
                f"  commit: {blame.get('commit', '?')}",
                f"  author: {blame.get('author', '?')}",
                f"  author_time: {blame.get('author_time', '?')}",
                f"  summary: {blame.get('summary', '?')}",
            )
        )
    return lines


def format_recent_commits_section(recent_commits: Any) -> list[str]:
    """Format recent commit metadata as plain text lines."""
    if not isinstance(recent_commits, list) or not recent_commits:
        return []
    lines = ["", "## Recent Commits"]
    for idx, entry in enumerate(recent_commits, 1):
        if not isinstance(entry, dict):
            continue
        commit = str(entry.get("commit") or "?")
        author = str(entry.get("author") or "?")
        when = str(entry.get("author_time") or "?")
        summary = str(entry.get("summary") or "")
        files = int(entry.get("files_changed") or 0)
        ins = int(entry.get("insertions") or 0)
        dele = int(entry.get("deletions") or 0)
        lines.append(f"{idx}. {commit} {when} {author}")
        lines.append(f"   {summary}")
        lines.append(f"   stats: files={files} +{ins} -{dele}")
    return lines


def format_crash_diffstat_section(diffstat: Any) -> list[str]:
    """Format crash file diffstat as plain text lines."""
    if not isinstance(diffstat, dict):
        return []
    touched = "true" if bool(diffstat.get("touched")) else "false"
    return [
        "",
        "## Crash File Diffstat",
        f"files_changed: {int(diffstat.get('files_changed') or 0)}",
        f"insertions: {int(diffstat.get('insertions') or 0)}",
        f"deletions: {int(diffstat.get('deletions') or 0)}",
        f"touched: {touched}",
    ]


def format_git_warnings_section(warnings: Any) -> list[str]:
    """Format git warning lines."""
    if not isinstance(warnings, list) or not warnings:
        return []
    lines = ["", "## Warnings"]
    lines.extend(f"- {warning}" for warning in warnings)
    return lines


def format_enhanced_git_context_text(context: dict[str, Any]) -> str:
    """Render enhanced git metadata as plain text."""
    lines: list[str] = []
    sections = (
        format_git_head_section(context.get("head")),
        format_crash_file_section(context.get("crash_file")),
        format_recent_commits_section(context.get("recent_commits")),
        format_crash_diffstat_section(context.get("crash_file_diffstat")),
        format_git_warnings_section(context.get("_git_warnings")),
    )
    for section in sections:
        lines.extend(section)

    if not lines:
        return "No enhanced git metadata available."
    return "\n".join(lines)
