#!/usr/bin/env python3
"""Add cross-brand links and script to all irish-online-casino pages."""

import re
from pathlib import Path

BASE = Path(__file__).resolve().parent
IRISH = BASE / "irish-online-casino"
EXCLUDE = {"terms", "privacy", "responsible-gambling", "disclaimer", "trust-badges", "contact"}

SCRIPT = '\n<script src="/irish-crossbrand.js"></script>'

# Replace the whole pattern
PAT_CTA = re.compile(
    r'<a href="/go/[^"]+" class="irish-cta-btn"[^>]*>'
)
REPL_CTA = '<a href="#" data-cb="1" class="irish-cta-btn" rel="nofollow sponsored noopener noreferrer" target="_blank">'

PAT_HERO = re.compile(
    r'<a href="/go/[^"]+" class="irish-cta-btn irish-hero-cta"[^>]*>'
)
REPL_HERO = '<a href="#" data-cb="1" class="irish-cta-btn irish-hero-cta" rel="nofollow sponsored noopener noreferrer" target="_blank">'

PAT_PLAY = re.compile(
    r'<a href="/go/[^"]+" class="irish-cta-play"[^>]*>'
)
REPL_PLAY = '<a href="#" data-cb="1" class="irish-cta-play" rel="nofollow sponsored noopener noreferrer" target="_blank">'

PAT_BEST = re.compile(
    r'<a href="/irish-online-casino/spin" class="irish-best-offer">'
)
REPL_BEST = '<a href="#" data-cb="1" class="irish-best-offer">'


def process_file(p: Path) -> bool:
    content = p.read_text(encoding="utf-8")
    orig = content

    content = PAT_HERO.sub(REPL_HERO, content)
    content = PAT_CTA.sub(REPL_CTA, content)
    content = PAT_PLAY.sub(REPL_PLAY, content)
    content = PAT_BEST.sub(REPL_BEST, content)

    needs_script = (PAT_CTA.search(orig) or PAT_HERO.search(orig) or PAT_PLAY.search(orig) or PAT_BEST.search(orig))
    if "irish-crossbrand.js" not in content and needs_script:
        # Add script before </body>
        content = content.replace("</body>", SCRIPT + "\n</body>", 1)

    if content != orig:
        p.write_text(content, encoding="utf-8")
        return True
    return False


def main():
    count = 0
    for item in sorted(IRISH.iterdir()):
        if not item.is_dir() or item.name in EXCLUDE:
            continue
        index = item / "index.html"
        if not index.exists():
            continue
        if process_file(index):
            count += 1
            print(index.parent.name)
    # Main index
    main_idx = IRISH / "index.html"
    if main_idx.exists() and process_file(main_idx):
        count += 1
        print("index")
    print(f"Done. Updated {count} files.")


if __name__ == "__main__":
    main()
