"""子项目级 `_overview.md` 索引。"""

from __future__ import annotations

from typing import Any

from niannian.vault.frontmatter import serialize_md
from niannian.vault.store import VaultStore


def overview_rel_path(*, namespace: str, category: str, subproject: str) -> str:
    return f"{namespace}/{category}/{subproject}/_overview.md"


def touch_overview(
    store: VaultStore,
    *,
    namespace: str,
    category: str,
    subproject: str,
    entry: dict[str, Any],
) -> dict[str, Any]:
    """import 后更新子项目 overview（标题 + vault_id 列表）。"""
    rel = overview_rel_path(namespace=namespace, category=category, subproject=subproject)
    try:
        existing = store.read_document(rel)
        fm = dict(existing.get("frontmatter") or {})
        body = str(existing.get("body") or "")
    except FileNotFoundError:
        fm = {
            "title": f"{subproject} 总览",
            "namespace": namespace,
            "category": category,
            "subproject": subproject,
            "source_type": "overview",
        }
        body = "## 资料索引\n\n"

    lines = [ln for ln in body.splitlines() if ln.strip()]
    if not any(ln.startswith("## ") for ln in lines):
        lines = ["## 资料索引", ""]
    vid = str(entry.get("vault_id") or "")
    title = str(entry.get("title") or "未命名")
    link = f"- [{title}]({vid}) `{vid}`"
    if vid and not any(vid in ln for ln in lines):
        lines.append(link)
    new_body = "\n".join(lines).strip() + "\n"
    abs_path = store._root / rel  # noqa: SLF001
    abs_path.parent.mkdir(parents=True, exist_ok=True)
    abs_path.write_text(serialize_md(fm, new_body), encoding="utf-8")
    store._track_file(f"vault/{rel}", abs_path)  # noqa: SLF001
    return {"rel_path": rel, "frontmatter": fm, "body": new_body}


def parse_overview_links(body: str) -> list[dict[str, str]]:
    out: list[dict[str, str]] = []
    for line in body.splitlines():
        line = line.strip()
        if not line.startswith("- ["):
            continue
        try:
            title = line.split("[", 1)[1].split("]", 1)[0]
            vid = line.split("`", 2)[1] if "`" in line else ""
        except IndexError:
            continue
        if vid:
            out.append({"title": title, "vault_id": vid})
    return out
