"""
Explainer — turns ContextResult into a readable natural language answer.

No API calls. No keys. No external dependencies.
Works instantly from the pre-built index.
"""

from __future__ import annotations

from ..context_engine.engine import ContextResult


def explain(result: ContextResult) -> str:
    """Answer the user's query in natural language from the indexed context."""
    if not result.modules:
        return f'Nothing found for: "{result.query}"'

    lines: list[str] = []

    top = result.modules[0]
    top_name = top.get("module") or top.get("file", "")
    top_summary = top.get("summary", "")

    # Lead
    if top_summary:
        lines.append(f"`{top_name}` — {top_summary}")
    else:
        lines.append(f"Most relevant: `{top_name}`")

    # Related modules
    if len(result.modules) > 1:
        others = [f"`{m.get('module') or m['file']}`" for m in result.modules[1:4]]
        lines.append(f"Also relevant: {', '.join(others)}.")

    # Key classes
    all_classes: list[str] = []
    for mod in result.modules[:3]:
        all_classes.extend(mod.get("classes", [])[:2])
    if all_classes:
        lines.append(f"Classes: {', '.join(all_classes[:5])}.")

    # Key functions
    all_fns: list[str] = []
    for mod in result.modules[:3]:
        all_fns.extend(mod.get("functions", [])[:3])
    if all_fns:
        lines.append(f"Functions: {', '.join(all_fns[:6])}.")

    # Dependency flow
    edges = result.graph_fragment.get("edges", [])
    if edges:
        flow = " → ".join(
            f"`{e.get('from','').split('/')[-1]}`" for e in edges[:3]
        )
        lines.append(f"Flow: {flow}.")

    # Git context
    git = top.get("git", {})
    if git.get("last_author"):
        lines.append(
            f"Last changed: {git['last_author']} — \"{git.get('last_message','')}\" ({git.get('last_date','')})"
        )

    return "\n".join(lines)
