from __future__ import annotations

import re
from pathlib import Path


APP_ROOT = Path(__file__).resolve().parents[1]
FRONTEND_ROOT = APP_ROOT / "frontend"
PAGE_MOUNT_MARKER = "    <!-- Registered page fragments mount here. -->\n"


def registered_frontend_fragments() -> list[str]:
    registry = (FRONTEND_ROOT / "pages.config.js").read_text(encoding="utf-8")
    return re.findall(
        r'^\s*\["[^"]+", "(/pages/[^"]+/page\.html(?:\?[^"]*)?)", \[',
        registry,
        re.MULTILINE,
    )


def registered_frontend_runtime_scripts() -> list[str]:
    registry = (FRONTEND_ROOT / "pages.config.js").read_text(encoding="utf-8")
    block = re.search(r"const runtimeScripts = \[(.*?)\n  \];", registry, re.DOTALL)
    if not block:
        raise AssertionError("runtimeScripts registry is missing")
    return re.findall(r'^\s*"([^"]+)",$', block.group(1), re.MULTILINE)


def assembled_frontend_document() -> str:
    shell = (FRONTEND_ROOT / "index.html").read_text(encoding="utf-8")
    if shell.count(PAGE_MOUNT_MARKER) != 1:
        raise AssertionError("index.html must contain exactly one page mount marker")
    fragments = []
    for url in registered_frontend_fragments():
        relative = url.split("?", 1)[0].lstrip("/")
        fragments.append((FRONTEND_ROOT / relative).read_text(encoding="utf-8"))
    return shell.replace(PAGE_MOUNT_MARKER, "".join(fragments))


def assembled_frontend_runtime() -> str:
    chunks = []
    for url in registered_frontend_runtime_scripts():
        relative = url.split("?", 1)[0].lstrip("/")
        if relative.startswith("vendor/"):
            continue
        chunks.append((FRONTEND_ROOT / relative).read_text(encoding="utf-8"))
    return "\n".join(chunks)
