"""Audit: for each starter page, find where the instructions div ACTUALLY closes
(handling nested </div> tags) and verify the appended text sits right before that close.
"""
import os, re

STARTERS = [
    "blank_starter", "calculator_starter", "calendar_starter", "chat_starter",
    "checklist_starter", "dashboard_starter", "form_starter", "gallery_starter",
    "generator_starter", "kanban_starter", "presentation_builder", "pulse_starter",
    "quiz_starter", "reference_starter", "roster_starter", "timeline_starter",
    "tutorial_starter",
]
LOCATIONS = ["default-pages", ".synthos/pages", "starters"]
APPEND_TEXT = "Use theme tokens (avoid the natural pallet) unless the user requests an alternative color."

OPEN_RE = re.compile(r'<div\b[^>]*>', re.IGNORECASE)
CLOSE_RE = re.compile(r'</div\s*>', re.IGNORECASE)
INSTR_OPEN = re.compile(r'<div id="instructions"[^>]*>', re.IGNORECASE)


def find_instructions_close(text: str) -> int | None:
    """Return index of the </div> that actually closes the instructions div,
    matching nested <div> tags correctly. Returns -1 if not found."""
    m = INSTR_OPEN.search(text)
    if not m:
        return None
    pos = m.end()
    depth = 1
    while pos < len(text) and depth > 0:
        next_open = OPEN_RE.search(text, pos)
        next_close = CLOSE_RE.search(text, pos)
        if not next_close:
            return -1
        if next_open and next_open.start() < next_close.start():
            depth += 1
            pos = next_open.end()
        else:
            depth -= 1
            if depth == 0:
                return next_close.start()
            pos = next_close.end()
    return -1


def main():
    root = os.path.abspath(os.path.dirname(__file__) + "/..")
    bad = []
    for starter in STARTERS:
        for loc in LOCATIONS:
            p = os.path.join(root, loc, starter, "page.html")
            if not os.path.exists(p):
                continue
            with open(p, "r", encoding="utf-8") as f:
                text = f.read()
            close_idx = find_instructions_close(text)
            if close_idx is None or close_idx < 0:
                bad.append((p, "no-close-found"))
                continue
            # Look back ~200 chars before the close for the appended text.
            window = text[max(0, close_idx - 250):close_idx]
            if APPEND_TEXT not in window:
                # Find ALL occurrences of the phrase and report their offsets vs the real close.
                phrase_at = []
                for m in re.finditer(re.escape(APPEND_TEXT), text):
                    phrase_at.append(m.start())
                bad.append((p, f"phrase-not-immediately-before-close (close@{close_idx}, phrase@{phrase_at})"))
    if not bad:
        print("OK — every file has the phrase immediately before the actual instructions-div close.")
    else:
        print(f"BAD — {len(bad)} files need fixing:")
        for p, reason in bad:
            print(f"  {p} :: {reason}")


if __name__ == "__main__":
    main()
