#!/usr/bin/env python3
"""Move the featured casino to the first row in 'Compared to Other Casinos' tables."""

import re
from pathlib import Path

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

# slug -> (name, bonus, min_dep, wager, logo) - for adding when casino not in table
CASINOS = {
    "20bet": ("20Bet Casino", "100% up to €500 + 120 FS", "€10", "35×", "20betcasino.webp"),
    "21-casino": ("21 Casino", "100% up to €121", "€10", "35×", "21casino.png"),
    "777-online": ("777 Casino", "Up to €1700 (5 dep)", "€20", "30×", "777onlinecasino.jpg"),
    "arena": ("Arena Casino", "100% €500 + 500 FS", "€1", "35×", "arenacasino.png"),
    "axe": ("Axe Casino", "100% up to €1500 + 200 FS", "€20", "45×", "axecasino.png"),
    "barz": ("Barz Casino", "100% up to €200 + 100 FS", "€10", "35×", "barzcasino.png"),
    "betinia": ("Betinia Casino", "100% up to €200 + 100 FS", "€10", "35×", "betiniacasino.png"),
    "betiton": ("Betiton Casino", "100% up to €150 + 150 FS", "€10", "35×", "betitoncasino.jpeg"),
    "bizzo": ("Bizzo Casino", "100% up to €100 + 100 FS", "€20", "40×", "bizzocasio.png"),
    "blackjack-casino": ("Blackjack Casino", "100% up to €500 + 50 FS", "€10", "35×", "blackjackcasino.avif"),
    "boho": ("Boho Casino", "100% up to €200 + 50 FS", "€10", "35×", "bohocasino.png"),
    "boo": ("Boo Casino", "Up to €1000 + 150 FS (3 dep)", "€20", "40×", "boocasino.png"),
    "captain-cooks": ("Captain Cooks Casino", "Up to €500 + 50 FS", "€10", "35×", "captaincookscasino.png"),
    "carlton": ("Carlton Casino", "100% up to €200 + 50 FS", "€10", "35×", "carltoncasino.svg"),
    "cocoa": ("Cocoa Casino", "100% up to €150 + 50 FS", "€10", "35×", "cocoacasino.png"),
    "cookie-casino": ("Cookie Casino", "100% up to €200 + 50 FS", "€5", "35×", "cookiecasino.webp"),
    "d1-casino": ("D1 Casino", "100% up to €150 + 50 FS", "€5", "35×", "d1casino.webp"),
    "dolly": ("Dolly Casino", "100% up to €300 + 100 FS", "€10", "35×", "dollycasino.webp"),
    "doggo": ("Doggo Casino", "100% up to €500 + 200 FS", "€20", "35×", "doggocasino.webp"),
    "dunder": ("Dunder Casino", "100% €600 + 200 FS", "€10", "35×", "dundercasino.png"),
    "energy": ("Energy Casino", "100% up to €200 + 100 FS", "€10", "35×", "energycasino.jpeg"),
    "friday-casino": ("Friday Casino", "100% up to €500 + 200 FS", "€10", "40×", "fridaycasino.webp"),
    "golden-star": ("Golden Star Casino", "Up to €1000 + 100 FS", "€10", "40×", "goldestarcasino.png"),
    "grand-mondial": ("Grand Mondial Casino", "100% up to €250 + 50 FS", "€10", "35×", "grandmondialcasino.png"),
    "hopa": ("Hopa Casino", "Up to €500 + 100 FS (3 dep)", "€10", "35×", "hopacasino.png"),
    "karamba": ("Karamba Casino", "100% up to €50 + 100 FS", "€10", "35×", "karambacasino.png"),
    "lucky-dreams": ("Lucky Dreams Casino", "100% up to €500 + 100 FS", "€10", "35×", "luckydreamscasino.png"),
    "mansion": ("Mansion Casino", "100% up to €200", "€20", "40×", "mansioncasino.png"),
    "mega": ("Mega Casino", "100% up to €200 + 125 FS", "€10", "30×", "megacasino.png"),
    "mr-play": ("Mr Play Casino", "200% €200 +100 FS", "€10", "35×", "mrplaycasino.png"),
    "my-empire": ("My Empire Casino", "100% up to €500 + 100 FS", "€10", "35×", "myempirecasino.svg"),
    "mystake": ("Mystake Casino", "300% up to €1500 (3 dep)", "€20", "30×", "mystakecasino.png"),
    "netent-casino": ("NetEnt Casino", "100% up to €200 + 100 FS", "€10", "35×", "netentcasino.png"),
    "phone-casino": ("Phone Casino", "100% up to €200 + 50 FS", "€10", "35×", "phonecasino.jpg"),
    "playzee": ("Playzee Casino", "100% £300 + 100 FS", "£20+", "10×", "playzeecasino.png"),
    "polestar": ("Polestar Casino", "100% up to €200 + 100 FS", "€10", "35×", "polestarcasino.webp"),
    "powbet": ("Powbet Casino", "100% €500 + 200 FS", "€10–20", "30×/40×", "powbetcasino.jpg"),
    "quatro": ("Quatro Casino", "100% up to €200 + 50 FS", "€10", "35×", "quatrocasino.webp"),
    "quickwin": ("Quickwin Casino", "100% up to €200 + 50 FS", "€10", "35×", "quickwincasino.webp"),
    "revolution": ("Revolution Casino", "100% up to €500 + 100 FS", "€10", "35×", "revolutioncasino.webp"),
    "rollino": ("Rollino Casino", "100% up to €200 + 50 FS", "€10", "35×", "rollinocasino.webp"),
    "scatters": ("Scatters Casino", "Risk-free $25", "€10", "No WR", "scatterscasino.png"),
    "spin": ("Spin Casino", "100% up to €1000 + 50 FS", "€10", "35×", "spincasino.png"),
    "spinia": ("Spinia Casino", "150% €250 +50 FS (2 dep)", "€20", "40×", "spiniacasino.png"),
    "star-casino": ("Star Casino", "100% up to €300 + 75 FS", "€10", "35×", "starcasino.jpeg"),
    "supersport": ("Supersport Casino", "100% up to €200 + 50 FS", "€10", "35×", "superspotcasino.jpg"),
    "tsars": ("Tsars Casino", "100% up to €500 + 100 FS", "€10", "35×", "tsarscasino.webp"),
    "vip-casino": ("VIP Casino", "100% up to €300 + 50 FS", "€10", "35×", "vipcasino.jpg"),
    "victoria": ("Victoria Casino", "100% up to €300 + 75 FS", "€10", "35×", "victoriacasino.png"),
    "winnerz": ("Winnerz Casino", "100% up to €300 + 100 FS", "€10", "35×", "winnerzcasino.png"),
    "zodiac": ("Zodiac Casino", "Up to €480 + 80 FS (3 dep)", "€1", "30×", "zodiaccasino.png"),
}
PAY_ICONS = '<img src="/publics/logos/visa.png" alt="Visa" class="irish-pay-mini" width="32" height="20"/><img src="/publics/logos/paypal.png" alt="PayPal" class="irish-pay-mini" width="32" height="20"/><img src="/publics/logos/applepay.jpg" alt="Apple Pay" class="irish-pay-mini" width="32" height="20"/>'


def extract_tbody(html: str) -> str | None:
    m = re.search(r'<h2>[^<]+ Casino Compared to Other Casinos</h2>.*?<tbody>\s*(.*?)\s*</tbody>', html, re.DOTALL)
    return m.group(1).strip() if m else None


def find_row_for_slug(rows: list[str], slug: str) -> str | None:
    """Find the <tr>...</tr> that links to this casino."""
    link = f'/irish-online-casino/{slug}"'
    for r in rows:
        if link in r:
            return r
    return None


def all_tr_rows(tbody: str) -> list[str]:
    """Split tbody into list of <tr>...</tr> strings."""
    return re.findall(r'<tr[^>]*>.*?</tr>', tbody, re.DOTALL)


def normalize_slug_from_path(path: Path) -> str:
    return path.parent.name


def make_featured_row(tr: str, badge: str = "You're here") -> str:
    """Add irish-editors-choice class and badge to the row."""
    tr = re.sub(r'\s*<span class="irish-editors-badge">[^<]*</span>\s*', ' ', tr)
    if re.match(r'<tr\s+class="', tr):
        tr = re.sub(r'<tr\s+class="([^"]*)"', r'<tr class="\1 irish-editors-choice"', tr, count=1)
        tr = re.sub(r'irish-editors-choice\s+irish-editors-choice', 'irish-editors-choice', tr)
    else:
        tr = tr.replace('<tr>', '<tr class="irish-editors-choice">', 1)
    # Add badge after casino name </a>
    # Insert before the optional existing badge - we already stripped it. Add after </a>
    tr = re.sub(r'(</a>)\s*', rf'\1 <span class="irish-editors-badge">{badge}</span> ', tr, count=1)
    return tr


def clean_row(r: str) -> str:
    r = re.sub(r'\s*<span class="irish-editors-badge">[^<]*</span>\s*', ' ', r)
    r = re.sub(r'\s*class="irish-editors-choice"\s*', ' ', r)
    r = re.sub(r'<tr\s+class="\s*"', '<tr', r)
    return r


def build_featured_row_from_casinos(slug: str) -> str | None:
    """Build a new row when casino is not in table."""
    if slug not in CASINOS:
        return None
    name, bonus, min_dep, wager, logo = CASINOS[slug]
    tr = f'<tr><td class="irish-casino-cell"><span class="irish-table-logo"><img src="/publics/casinos/{logo}" alt="" onerror="this.style.display=\'none\'"/></span><a href="/irish-online-casino/{slug}">{name}</a></td><td>{bonus}</td><td>{min_dep}</td><td>{wager}</td><td class="irish-payments-cell">{PAY_ICONS}</td><td class="irish-action-cell"><a href="/go/{slug}" class="irish-cta-btn" rel="nofollow sponsored noopener noreferrer" target="_blank">Play Now</a> <a href="/irish-online-casino/{slug}" class="irish-table-review">Read full review</a></td></tr>'
    return make_featured_row(tr)


def process_page(index_path: Path, slug: str) -> bool:
    content = index_path.read_text(encoding="utf-8")
    tbody = extract_tbody(content)
    if not tbody:
        return False
    rows = all_tr_rows(tbody)
    if not rows:
        return False

    featured_tr = find_row_for_slug(rows, slug)
    link = f'/irish-online-casino/{slug}"'
    if not featured_tr:
        featured_tr = build_featured_row_from_casinos(slug)
        if not featured_tr:
            return False
        first_row = featured_tr
        new_rows = [clean_row(r) for r in rows]
    else:
        first_row = make_featured_row(featured_tr)
        new_rows = [clean_row(r) for r in rows if link not in r]

    new_tbody = "\n" + first_row + "\n" + "\n".join(new_rows) + "\n"
    old_block = re.search(
        r'(<h2>[^<]+ Casino Compared to Other Casinos</h2>.*?<tbody>)\s*.*?\s*(</tbody>)',
        content,
        re.DOTALL
    )
    if not old_block:
        return False
    content_new = content.replace(
        old_block.group(0),
        old_block.group(1) + new_tbody + old_block.group(2),
        1
    )
    index_path.write_text(content_new, encoding="utf-8")
    return True


def main():
    for p in sorted(BASE.iterdir()):
        if not p.is_dir() or p.name in EXCLUDE:
            continue
        index = p / "index.html"
        if not index.exists():
            continue
        slug = p.name
        if process_page(index, slug):
            print(f"OK: {slug}")
        else:
            print(f"skip: {slug} (no table or casino not in list)")
    print("Done.")


if __name__ == "__main__":
    main()
