"""One-shot: append the theme-tokens instruction to every starter's instructions div.

Excludes retro_game_starter. Edits the same starter in all 3 locations:
  default-pages/<name>/page.html
  .synthos/pages/<name>/page.html
  starters/<name>/page.html
"""
import os
import re
import sys

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."

# Match opening tag of the instructions div, then non-greedy capture up to its closing </div>.
INSTRUCTIONS_RE = re.compile(
    r'(<div id="instructions"[^>]*>)(.*?)(</div>)',
    re.DOTALL,
)

def update(path: str) -> str:
    with open(path, "r", encoding="utf-8") as f:
        original = f.read()

    matched = []

    def replace(m):
        opening, body, closing = m.group(1), m.group(2), m.group(3)
        if APPEND_TEXT.strip() in body:
            matched.append("skip-already-present")
            return m.group(0)
        # Preserve trailing whitespace/newlines before </div>.
        trailing_ws = re.search(r"\s*$", body).group(0)
        body_trimmed = body[: len(body) - len(trailing_ws)]
        new_body = body_trimmed + APPEND_TEXT + trailing_ws
        matched.append("ok")
        return opening + new_body + closing

    updated, count = INSTRUCTIONS_RE.subn(replace, original, count=1)
    if count == 0:
        return "no-match"
    if matched and matched[0] == "skip-already-present":
        return "already"
    if updated != original:
        with open(path, "w", encoding="utf-8", newline="") as f:
            f.write(updated)
        return "updated"
    return "noop"


def main():
    root = os.path.abspath(os.path.dirname(__file__) + "/..")
    results = []
    for starter in STARTERS:
        for loc in LOCATIONS:
            p = os.path.join(root, loc, starter, "page.html")
            if not os.path.exists(p):
                results.append((p, "missing"))
                continue
            results.append((p, update(p)))
    by_status = {}
    for path, status in results:
        by_status.setdefault(status, []).append(path)
    for status, paths in by_status.items():
        print(f"[{status}] {len(paths)}")
        for p in paths:
            print(f"  {p}")


if __name__ == "__main__":
    main()
