"""
Why — answers the question "WHY does this file exist?"

Combines:
  - git history: commit messages for the file (last N commits)
  - notes: developer annotations from NotesStore if any
  - module summary from the index
  - dependents: who depends on this file

Does NOT call any LLM — purely structured data from git + index.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

from ..memory.store import KodaraIndex


def _resolve_path_local(modules: dict, target: str) -> str | None:
    """Match target to an indexed path. Tries exact, then suffix, then stem."""
    if target in modules:
        return target
    target_norm = target.replace("\\", "/")
    for path in modules:
        path_norm = path.replace("\\", "/")
        if path_norm.endswith(target_norm) or path_norm.endswith("/" + target_norm):
            return path
    target_stem = Path(target).stem.lower()
    for path in modules:
        if Path(path).stem.lower() == target_stem:
            return path
    return None


@dataclass
class WhyResult:
    file: str                          # absolute path of the file
    module_name: str                   # stem name
    git_reason: str                    # last meaningful commit message (or empty)
    git_commits: int                   # total commit count
    git_authors: list[dict]            # [{name, commits}]
    notes: list[str]                   # developer annotations (text only)
    summary: str                       # module summary from index
    dependents_count: int              # how many modules depend on this file
    dependents: list[str]              # paths of dependents (up to 10)


def get_why(
    index: KodaraIndex,
    target_path: str,
    notes_store=None,              # Optional[NotesStore] — lazy to avoid hard dep
    max_commits: int = 5,
) -> WhyResult:
    """
    Build a WhyResult for target_path.

    Args:
        index:       KodaraIndex loaded from MemoryStore
        target_path: file path (absolute or relative — fuzzy matched)
        notes_store: optional NotesStore instance
        max_commits: how many recent commits to surface

    Returns:
        WhyResult — never raises, always returns something sensible.
    """
    resolved = _resolve_path_local(index.modules, target_path)
    if not resolved:
        # Graceful fallback: return an empty result for unknown files
        return WhyResult(
            file=target_path,
            module_name=Path(target_path).stem,
            git_reason="",
            git_commits=0,
            git_authors=[],
            notes=[],
            summary="",
            dependents_count=0,
            dependents=[],
        )

    mod = index.modules.get(resolved, {})
    git = mod.get("git", {})

    # Git data
    git_reason = git.get("last_message", "")
    git_commits = git.get("commit_count", 0)
    git_authors = git.get("top_authors", [])

    # Module summary
    summary = mod.get("summary", "")

    # Dependents
    dep_list = mod.get("dependents", [])
    dependents_count = len(dep_list)
    dependents = dep_list[:10]

    # Notes
    notes: list[str] = []
    if notes_store is not None:
        try:
            raw_notes = notes_store.get(resolved)
            notes = [n.text for n in raw_notes]
        except Exception:
            pass

    return WhyResult(
        file=resolved,
        module_name=mod.get("module_name", Path(resolved).stem),
        git_reason=git_reason,
        git_commits=git_commits,
        git_authors=git_authors,
        notes=notes,
        summary=summary,
        dependents_count=dependents_count,
        dependents=dependents,
    )


def get_why_ai(index, file: str) -> "str | None":
    """Call Kodara backend for AI explanation. Requires active session (Pro)."""
    try:
        from kodara.cloud.client import load_session
        session = load_session()
        if not session:
            return None

        access_token = session.get("access_token") or session.get("token")
        if not access_token:
            return None

        why = get_why(index, file)
        prompt = (
            f"File: {file}\n"
            f"Summary: {(why.summary or '')[:200]}\n"
            f"Recent commits: {', '.join(([why.git_reason] if why.git_reason else []))}\n"
            f"In 2-3 sentences: why does this file exist and what problem does it solve?"
        )

        import httpx
        resp = httpx.post(
            "https://getkodara.dev/api/llm",
            json={"prompt": prompt, "session_token": access_token},
            timeout=10.0,
        )
        if resp.status_code == 200:
            return resp.json().get("text")
        return None
    except Exception:
        return None
