#!/usr/bin/env python3
"""Loader for the ASU syllabus policy boilerplate asset.

The verbatim ASU Online QM-template policy sections live in
``standards/asu-syllabus-boilerplate.html``.  This module provides two
pure, network-free helpers for consuming that asset:

* :func:`load_boilerplate` — returns the full HTML string.
* :func:`boilerplate_sections` — returns a ``dict[str, str]`` mapping
  each section title to its HTML block (heading + body).

These are the *only* authorised entry points for the boilerplate.
``syllabus-generator`` injects the result verbatim — it must NOT
regenerate institutional policy prose from scratch.
"""

import os
import re
from typing import Dict

# Resolve asset path relative to this file (scripts/ → standards/)
_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_ASSET_PATH = os.path.join(_REPO_ROOT, "standards", "asu-syllabus-boilerplate.html")


def load_boilerplate() -> str:
    """Return the full boilerplate HTML as a string.

    Reads ``standards/asu-syllabus-boilerplate.html`` from the repo root.
    Pure; no network calls.

    Returns
    -------
    str
        Complete HTML content of the boilerplate asset.

    Raises
    ------
    FileNotFoundError
        If the asset file is missing (should never happen in a clean checkout).
    """
    with open(_ASSET_PATH, "r", encoding="utf-8") as fh:
        return fh.read()


def boilerplate_sections() -> Dict[str, str]:
    """Return a mapping of section title → section HTML.

    Each section is delimited by a ``<!-- SECTION: <Title> -->`` comment in
    the asset file.  The returned dict value for each key includes the
    opening ``<!-- SECTION: ... -->`` comment, the ``<h2>`` heading, and all
    body content up to (but not including) the next ``<!-- SECTION: ... -->``
    comment or end of file.

    Section titles are normalised: leading/trailing whitespace stripped.

    Pure; no network calls.

    Returns
    -------
    dict[str, str]
        Keys are section titles exactly as written in the ``SECTION:``
        comments (e.g. ``"Academic Integrity"``, ``"Syllabus Disclaimer"``).
        Values are the raw HTML for each section block.
    """
    html = load_boilerplate()

    # Split on section delimiters — keep the delimiter with its section
    delimiter_re = re.compile(r'(?=<!-- SECTION:)')
    chunks = delimiter_re.split(html)

    sections: Dict[str, str] = {}
    title_re = re.compile(r'<!-- SECTION:\s*(.+?)\s*-->', re.DOTALL)

    for chunk in chunks:
        chunk = chunk.strip()
        if not chunk:
            continue
        m = title_re.match(chunk)
        if m:
            title = m.group(1).strip()
            sections[title] = chunk

    return sections
