#!/usr/bin/env python3
"""Insert partner-shop affiliate boxes into retro articles just before <h2>Quellen</h2>."""

import sys, os

WORKSPACE = "/home/hermes/workspace"
LINKS_DIR = "/tmp/retro_links"

# Map: safe_filename (in /tmp/retro_links/) -> article filename
GAMES = [
    ("Gloomhaven", "artikel_gloomhaven_retro_2026-06-15.html"),
    ("Spirit_Island", "artikel_spirit_island_retro_2026-06-15.html"),
    ("Wingspan", "artikel_wingspan_retro_2026-06-15.html"),
    ("Root", "artikel_root_retro_2026-06-15.html"),
    ("Nemesis", "artikel_nemesis_retro_2026-06-15.html"),
    ("7th_Continent", "artikel_7th_continent_retro_2026-06-15.html"),
    ("Tainted_Grail", "artikel_tainted_grail_retro_2026-06-15.html"),
    ("Sleeping_Gods", "artikel_sleeping_gods_retro_2026-06-15.html"),
    ("Oathsworn", "artikel_oathsworn_retro_2026-06-15.html"),
    ("Blood_on_the_Clocktower", "artikel_blood_on_the_clocktower_retro_2026-06-15.html"),
    ("Earthborne_Rangers", "artikel_earthborne_rangers_retro_2026-06-15.html"),
    ("Captain_Sonar", "artikel_captain_sonar_retro_2016_2026-06-12.html"),
    ("Vast-_The_Crystal_Caverns", "artikel_vast_crystal_caverns_retro_2016_2026-06-12.html"),
    ("The_Colonists", "artikel_the_colonists_retro_2016_2026-06-12.html"),
]

inserted = 0
skipped = 0

for safe_name, article_file in GAMES:
    snippet_path = os.path.join(LINKS_DIR, f"{safe_name}.html")
    article_path = os.path.join(WORKSPACE, article_file)

    if not os.path.exists(snippet_path):
        print(f"SKIP {article_file}: no snippet at {snippet_path}")
        skipped += 1
        continue

    if not os.path.exists(article_path):
        print(f"SKIP {article_file}: article not found")
        skipped += 1
        continue

    with open(snippet_path) as f:
        snippet = f.read().strip()

    if not snippet or 'affiliate-box' not in snippet:
        print(f"SKIP {article_file}: snippet empty or invalid")
        skipped += 1
        continue

    with open(article_path) as f:
        article = f.read()

    if 'affiliate-box' in article:
        print(f"SKIP {article_file}: already has affiliate box")
        skipped += 1
        continue

    # Insert before <h2>Quellen</h2>
    if '<h2>Quellen</h2>' not in article:
        print(f"WARN {article_file}: no <h2>Quellen</h2> found, skipping")
        skipped += 1
        continue

    article = article.replace('<h2>Quellen</h2>', snippet + '\n\n<h2>Quellen</h2>', 1)

    with open(article_path, 'w') as f:
        f.write(article)

    print(f"OK   {article_file}")
    inserted += 1

print(f"\nDone. Inserted: {inserted}, Skipped: {skipped}")
