"""Reference-list generation from Deep Research sources.jsonl."""

from __future__ import annotations

import json
import re
from pathlib import Path


def cited_source_keys(md_text: str) -> set[str]:
    return set(re.findall(r"\[src_([a-zA-Z0-9_-]+)\]", md_text))


def build_references_block(sources_path: Path | None, md_text: str) -> str:
    """Build a compact references section for actually cited src IDs."""
    if not sources_path or not sources_path.exists():
        return "（参考文献列表：sources.jsonl 未找到）"

    cited = cited_source_keys(md_text)
    if not cited:
        return ""

    sources: dict[str, dict] = {}
    with sources_path.open(encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                obj = json.loads(line)
            except json.JSONDecodeError:
                continue
            sid = obj.get("id", "")
            key = sid.replace("src_", "")
            if key in cited:
                sources[sid] = obj

    if not sources:
        return ""

    lines = ["## 参考文献\n"]
    for sid in sorted(sources.keys()):
        s = sources[sid]
        authors = ", ".join(s.get("authors", [])) if s.get("authors") else ""
        year = s.get("year", "")
        title = s.get("title", sid)
        venue = s.get("venue", "")
        url = s.get("url", "")
        entry = f"- **[{sid}]** "
        if authors:
            entry += f"{authors}. "
        if year:
            entry += f"({year}). "
        entry += f"*{title}*"
        if venue:
            entry += f". {venue}"
        if url:
            entry += f". <{url}>"
        lines.append(entry)
    return "\n".join(lines)

