# -*- coding: utf-8 -*-
"""Unify header + newsletter + footer on branch pages with locations.html template."""
from pathlib import Path
import re

ROOT = Path(__file__).resolve().parent
LOC = ROOT / "locations.html"
text = LOC.read_text(encoding="utf-8")

i1 = text.find('<div id="header">')
i2 = text.find('<main id="locations">')
if i1 < 0 or i2 < 0:
    raise SystemExit(f"header markers not found: {i1} {i2}")
# Include full #header closing </div> (ends immediately before <main> on locations page)
header = text[i1:i2]

i3 = text.find('<div id="newsletter">')
if i3 < 0:
    raise SystemExit("newsletter not found")
j = text.find("<script>", i3)
if j < 0:
    raise SystemExit("script after newsletter not found")
tail = text[i3:j]

P = "../../"

# Page filenames at site root (relative links in template)
_ROOT_PAGES = (
    "index.html",
    "about-us.html",
    "menu.html",
    "gallery.html",
    "locations.html",
    "contact-us.html",
    "careers.html",
)


def relink(s: str) -> str:
    for page in _ROOT_PAGES:
        s = s.replace(f'href="{page}"', f'href="{P}{page}"')
    # Local archived asset paths (timestamp folders)
    s = re.sub(r'(?<!\.{2}/)(src=")(202[0-9]+im_/)', rf"\1{P}\2", s)
    s = re.sub(r"(url\(')(202[0-9]+im_/)", rf"\1{P}\2", s)
    return s


header_r = relink(header)
tail_r = relink(tail)

BRANCH_FILES = [
    ROOT / "locations" / "al-munsiyah" / "al-munsiyah.html",
    ROOT / "locations" / "al-shifa" / "index.html",
    ROOT / "locations" / "al-badiaa-" / "al-badiaa-.html",
    ROOT / "locations" / "al-hamra-" / "index.html",
    ROOT / "locations" / "al-maathar-" / "index.html",
    ROOT / "locations" / "assulimaniyah" / "index.html",
    ROOT / "locations" / "arrabwah" / "index.html",
    ROOT / "locations" / "alrabie-branch-" / "index.html",
    ROOT / "locations" / "hittin-branch" / "index.html",
]

main_pat = re.compile(
    r'<main id="locations-single"[^>]*>.*?</main>',
    re.DOTALL | re.IGNORECASE,
)

JQ_MARKER = '\t\t<script>\n\t!function(a,b)'


def find_jquery_script_start(t: str, after_pos: int) -> int:
    idx = t.find(JQ_MARKER, after_pos)
    if idx >= 0:
        return idx
    inner = t.find('!function(a,b){"use strict"', after_pos)
    if inner < 0:
        return -1
    return t.rfind("<script>", after_pos, inner + 1)


for fpath in BRANCH_FILES:
    if not fpath.exists():
        print("SKIP missing:", fpath)
        continue
    t = fpath.read_text(encoding="utf-8")
    mm = main_pat.search(t)
    if not mm:
        print("SKIP no main:", fpath)
        continue
    main_block = mm.group(0)
    h_start = t.find('<div id="header">')
    if h_start < 0:
        print("SKIP no header:", fpath)
        continue
    main_start = t.find("<main id=", h_start)
    if main_start < 0:
        print("SKIP no main tag:", fpath)
        continue
    main_end = t.find("</main>", main_start)
    if main_end < 0:
        print("SKIP no </main>:", fpath)
        continue
    main_end += len("</main>")
    jq = find_jquery_script_start(t, main_end)
    if jq < 0:
        print("SKIP no jquery script:", fpath)
        continue
    prefix = t[:h_start]
    suffix = t[jq:]
    new_t = prefix + header_r + main_block + tail_r + suffix
    fpath.write_text(new_t, encoding="utf-8")
    print("OK", fpath.relative_to(ROOT))

print("Done.")
