"""Rewrite the `/en/company/references/` Basic Page body so the hardcoded
teaser grid becomes a `<div data-references-grid></div>` placeholder. At
render time, kaindl_references_preprocess_node() swaps that placeholder with a
dynamic grid queried from reference nodes.

The filter-bar markup (Boards / Wood Veneered Boards / Floors checkboxes) is
retained and gets an interactive JS behaviour from the module's `listing`
library.

Usage:
    python scripts/references/build_references_index.py

Idempotent: reruns produce the same body.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[2]
PAGES_JSON = PROJECT_ROOT / "web" / "modules" / "custom" / "kaindl_pages" / "data" / "pages-content.en.json"

SOURCE_KEY = "/en/company/references/"

FILTER_BAR_HTML = """\
<section class="page-body__section section-spacer">
  <div class="references-filter" data-references-filter>
    <p class="references-filter__label">Filter by</p>
    <ul class="references-filter__items">
      <li class="references-filter__item">
        <label><input type="checkbox" name="Boards" checked> Boards</label>
      </li>
      <li class="references-filter__item">
        <label><input type="checkbox" name="Wood Veneered Boards" checked> Wood Veneered Boards</label>
      </li>
      <li class="references-filter__item">
        <label><input type="checkbox" name="Floors" checked> Floors</label>
      </li>
    </ul>
  </div>
  <div data-references-grid></div>
</section>
"""


def main() -> None:
    if not PAGES_JSON.exists():
        sys.stderr.write(f"missing {PAGES_JSON}\n")
        sys.exit(1)

    data = json.loads(PAGES_JSON.read_text(encoding="utf-8"))
    pages = data.get("pages") or []
    for page in pages:
        if str(page.get("source_key") or "") == SOURCE_KEY:
            new_body = '<article class="page-body" data-references-index="true">' + FILTER_BAR_HTML + "</article>"
            page["body"] = new_body
            PAGES_JSON.write_text(
                json.dumps(data, ensure_ascii=False, indent=2) + "\n",
                encoding="utf-8",
            )
            sys.stderr.write("Rewrote index body — body length %d chars.\n" % len(new_body))
            return

    sys.stderr.write(f"No page entry found for {SOURCE_KEY}; nothing changed.\n")
    sys.exit(1)


if __name__ == "__main__":
    main()
