"""
Merge a generated API navigation tree into zensical.toml while preserving
formatting, comments, and inline-table structure.

Inputs:
- zensical.toml
  Base Zensical configuration containing `[project] nav = [...]`.

- nav.generated.toml
  A TOML snippet containing a top-level `nav = [...]` definition,
  typically generated automatically (e.g. from API docs).

Output:
- zensical.generated.toml
  The merged configuration, with the "API Reference" nav entry replaced
  (or appended if missing), preserving the original TOML formatting.
"""

from __future__ import annotations

from pathlib import Path

import tomlkit

BASE = Path("zensical.toml")
NAV_SNIPPET = Path("nav.generated.toml")
OUT = Path("zensical.generated.toml")


def main() -> None:
    """Merge the generated API Reference navigation into the base config."""
    if not BASE.exists():
        raise FileNotFoundError(f"Missing base config: {BASE}")

    if not NAV_SNIPPET.exists():
        raise FileNotFoundError(f"Missing nav snippet: {NAV_SNIPPET}")

    doc = tomlkit.parse(BASE.read_text(encoding="utf-8"))
    snippet_doc = tomlkit.parse(NAV_SNIPPET.read_text(encoding="utf-8"))

    if "nav" not in snippet_doc:
        raise ValueError("nav.generated.toml must contain a top-level `nav = [...]`")

    generated_nav = snippet_doc["nav"]

    try:
        nav = doc["project"]["nav"]
    except KeyError as exc:
        raise ValueError("zensical.toml must contain `[project] nav = [...]`") from exc

    # Replace the existing "API Reference" entry, or append it if missing
    for item in nav:
        if isinstance(item, dict) and "API Reference" in item:
            item["API Reference"] = generated_nav
            break
    else:
        nav.append({"API Reference": generated_nav})

    OUT.write_text(tomlkit.dumps(doc), encoding="utf-8")
    print(f"Generated {OUT}")


if __name__ == "__main__":
    main()
