#!/usr/bin/env python3
"""gen_llm_txt.py — Rebuild llm.txt from the generated docs.

Run from the repository root:
    uv run python scripts/gen_llm_txt.py

Concatenates the auto-generated API reference, changelog, and key docs into a
compact, LLM-friendly plain-text file at llm.txt.  Run *after*
gen_api_reference.py and sync_changelog.py.
"""

from __future__ import annotations

import re
from pathlib import Path

ROOT = Path(__file__).parent.parent
LLM_TXT = ROOT / "llm.txt"
DOCS_LLM_TXT = ROOT / "docs" / "llm.txt"

SOURCES = [
    ("API Reference", ROOT / "docs" / "api-reference.md"),
    ("Changelog", ROOT / "docs" / "changelog.md"),
    ("Architecture", ROOT / "docs" / "architecture.md"),
    ("Getting Started", ROOT / "docs" / "getting-started.md"),
]

HEADER = """\
# networkXR — LLM context file
# Auto-generated by scripts/gen_llm_txt.py — do not edit by hand.
# Source: https://github.com/bmsuisse/networkXR

"""


def _strip_html_comments(text: str) -> str:
    return re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)


def main() -> None:
    parts = [HEADER]
    for title, path in SOURCES:
        if not path.exists():
            print(f"  ⚠ Skipping {path.name} (not found)")
            continue
        text = path.read_text(encoding="utf-8")
        text = _strip_html_comments(text)
        parts.append(f"\n\n{'=' * 80}\n## {title}\n{'=' * 80}\n\n")
        parts.append(text)

    content = "".join(parts)
    LLM_TXT.write_text(content, encoding="utf-8")
    DOCS_LLM_TXT.write_text(content, encoding="utf-8")
    print(f"✔ Wrote {LLM_TXT.relative_to(ROOT)}  ({len(content):,} chars)")
    print(f"✔ Wrote {DOCS_LLM_TXT.relative_to(ROOT)}  ({len(content):,} chars)")


if __name__ == "__main__":
    main()
