#!/usr/bin/env python3
"""
Re-brand the downloaded index.html for Africatis and strip the original
site's third-party accounts (analytics, pixels, chat, booking engine).

Run after download_site.py:   python rebrand.py
It reads _source/index.mirror.html (the un-branded local copy) and writes
index.html, so you can edit the BRAND block below and run it again.
"""
import json
import re
from pathlib import Path

BRAND = {
    "name": "Africatis",
    "title": "Africatis",
    "phone_display": "+254 712 345 678",
    "phone_tel": "+254712345678",
    "whatsapp": "254712345678",
    "address_lines": ["Uganda Road", "Eldoret, Uasin Gishu", "Kenya"],
    "street": "Uganda Road", "city": "Eldoret", "region": "Uasin Gishu",
    "country": "KE",
    "logo_colour": "images/africatis-logo-colour.png",
    "logo_white": "images/africatis-logo-white.png",
    "favicon": "images/africatis-favicon-{0}x{0}.png",
}

ROOT = Path(__file__).resolve().parent
ROOT = ROOT.parent if ROOT.name == "_source" else ROOT
page = ROOT / "index.html"
# Always start from the un-branded local copy so this can be re-run safely
mirror = ROOT / "_source" / "index.mirror.html"
if not mirror.exists():
    mirror.write_text(page.read_text(encoding="utf-8"), encoding="utf-8", newline="")
s = mirror.read_text(encoding="utf-8")
before = len(s)

# 1. Third-party services tied to the original site's accounts ------------
SCRIPT = r"<script\b[^>]*>.*?</script>"
drop_scripts = [
    r"cdn-cookieyes\.com", r"googletagmanager\.com/gtag", r"gtag\('config'",
    r"gtm\.start", r"fbq\(", r"_hsq", r"hs-script-loader", r"Tawk_API",
    r"upperbooking\.com", r"leadin_wordpress",
]
def kill_script(m):
    return "" if any(re.search(p, m.group(0)) for p in drop_scripts) else m.group(0)
s = re.sub(SCRIPT, kill_script, s, flags=re.S | re.I)
s = re.sub(r"<noscript>\s*<img[^>]*facebook\.com/tr[^>]*>\s*</noscript>", "", s)
s = re.sub(r"<noscript>\s*<iframe[^>]*googletagmanager[^>]*>\s*</iframe>\s*</noscript>", "", s, flags=re.S)

# 2. Head metadata that points at the original site ----------------------
s = re.sub(r"<link\s+rel=[\"'](?:canonical|shortlink|alternate|EditURI|https://api\.w\.org/)[\"'][^>]*>", "", s)
s = re.sub(r"<link\s+rel=[\"']dns-prefetch[\"']\s+href=[\"']//js-eu1\.hs-scripts\.com[\"'][^>]*>", "", s)
s = re.sub(r"<meta\s+(?:property=\"og:url\"|name=\"google-site-verification\")[^>]*>", "", s)
s = re.sub(r"<meta\s+name=\"twitter:(?:site|creator|label\d|data\d)\"[^>]*>", "", s)
s = re.sub(r"<title>.*?</title>", f"<title>{BRAND['title']}</title>", s, count=1, flags=re.S)
for prop in ("og:title", "twitter:title"):
    s = re.sub(rf'(<meta\s+(?:property|name)="{prop}"\s+content=")[^"]*"',
               rf'\g<1>{BRAND["title"]}"', s)

# Replace the SEO schema with a small one describing Africatis
schema = {
    "@context": "https://schema.org", "@type": "Organization",
    "name": BRAND["name"], "telephone": BRAND["phone_tel"],
    "logo": BRAND["logo_colour"],
    "address": {"@type": "PostalAddress", "streetAddress": BRAND["street"],
                "addressLocality": BRAND["city"],
                "addressRegion": BRAND["region"],
                "addressCountry": BRAND["country"]},
}
s = re.sub(r'<script type="application/ld\+json"[^>]*>.*?</script>',
           '<script type="application/ld+json">' + json.dumps(schema) + "</script>",
           s, count=1, flags=re.S)

# 3. Logo and favicons ---------------------------------------------------
s = s.replace("images/Saruni-Basecamp-Brand-Colour.png", BRAND["logo_colour"])
s = s.replace("images/Saruni-Basecamp-Brand-white.png", BRAND["logo_white"])
s = re.sub(r'alt="Saruni Basecamp Brand (?:Colour|white)"',
           f'alt="{BRAND["name"]}"', s)
s = re.sub(r"images/cropped-Saruni-Basecamp-Brand-fauvicon-(\d+)x\d+\.png",
           lambda m: BRAND["favicon"].format(m.group(1)), s)

# 4. Name, phone, WhatsApp -------------------------------------------------
s = s.replace("Saruni Basecamp", BRAND["name"])
for old in ("+254 796 222 555", "+254 735 950 903"):
    s = s.replace(old, BRAND["phone_display"])
s = s.replace("tel:+254796222555", "tel:" + BRAND["phone_tel"])
s = s.replace("wa.me/254735950903", "wa.me/" + BRAND["whatsapp"])

# 5. Footer contact block gets the address -------------------------------
addr = "<br />".join(BRAND["address_lines"])
s = s.replace("<h4>Kenya, Maasai Mara &amp; Samburu</h4>",
              f'<h4>{BRAND["name"]}</h4><p class="p1">{addr}</p>')

# 6. Language-switcher flags served from images/flags/svg/ --------------
s = s.replace('"flags_location":"\\/wp-content\\/plugins\\/gtranslate\\/flags\\/"',
              '"flags_location":"images\\/flags\\/"')

page.write_text(s, encoding="utf-8", newline="")
print(f"index.html updated ({before:,} -> {len(s):,} chars)")
