#!/usr/bin/env python3
"""Parse kinderspiele_deals HTML and build Joomla article."""
import re, json, sys

with open("/home/hermes/workspace/kinderspiele_deals_2026-06-21.html") as f:
    html = f.read()

# Extract deal blocks - each is a <div>...</div> with the deal info
# Pattern: <div style="display:flex;..."> <img src="URL"> ... <strong>TITLE</strong> ... price ... UVP ... -PCT% ... dp/ASIN?tag
blocks = re.split(r'<div style="display:flex;gap:1rem;padding:1rem 0;border-bottom:1px solid #eee;">', html)[1:]

deals = []
for block in blocks:
    # Extract fields
    img_match = re.search(r'<img src="([^"]+)"', block)
    title_match = re.search(r'<strong>([^<]+)</strong>', block)
    price_match = re.search(r'font-weight:bold;">([\d.]+)\s*€<', block)
    uvp_match = re.search(r'UVP\s+([\d.]+)\s*€<', block)
    pct_match = re.search(r'-(\d+)%<', block)
    saved_match = re.search(r'>\(([\d.]+)\s*€\s*gespart\)<', block)
    asin_match = re.search(r'/dp/([A-Z0-9]+)\?tag', block)

    if all([img_match, title_match, price_match, uvp_match, pct_match, saved_match, asin_match]):
        deals.append({
            "img": img_match.group(1),
            "title": title_match.group(1).strip(),
            "price": float(price_match.group(1)),
            "uvp": float(uvp_match.group(1)),
            "pct": int(pct_match.group(1)),
            "saved": float(saved_match.group(1)),
            "asin": asin_match.group(1),
        })

print(f"Parsed {len(deals)} deals", file=sys.stderr)

def categorize(title):
    tl = title.lower()
    if 'ab 2 jahr' in tl or 'meine ersten spiele' in tl or '2 jahre' in tl and 'ab 2' in tl:
        return "2+"
    if 'ab 3 jahr' in tl or '3 jahre' in tl and 'ab 3' in tl:
        return "3+"
    if 'ab 4 jahr' in tl or '4 jahre' in tl and 'ab 4' in tl or 'vorschul' in tl:
        return "4+"
    if 'ab 5 jahr' in tl or '5 jahre' in tl and 'ab 5' in tl:
        return "5+"
    if 'ab 6 jahr' in tl or '6-9 jahre' in tl or 'ab 6' in tl:
        return "6+"
    if 'ab 7 jahr' in tl:
        return "7+"
    known = {
        'monsterjäger': '5+', 'paletti spaghetti': '5+', 'topp die torte': '5+',
        'pupsparade': '4+', 'kinderspiele klassiker': '4+', 'sagaland': '6+',
        'kristallica': '4+', 'lotti karotti': '4+', 'milly muffin': '4+',
        'kroko doc': '4+', 'kakerlakak': '5+', 'sos affenalarm': '5+',
        'scrabble junior': '6+', 'wer war': '6+', 'magischen schlüssel': '6+',
        'magic 8 ball': '7+', 'wort für wort': '6+', 'erster obstgarten': '2+',
        'hanni honigbiene': '2+', 'sachen suchen': '2+',
    }
    for key, age in known.items():
        if key in tl:
            return age
    return "Allgemein"

age_groups = {}
for d in deals:
    age = categorize(d['title'])
    if age not in age_groups:
        age_groups[age] = []
    age_groups[age].append(d)

# Output structured data as JSON for next step
output = {
    "deals": deals,
    "age_groups": {k: [{"title": d['title'], "price": d['price'], "uvp": d['uvp'],
                         "pct": d['pct'], "saved": d['saved'], "asin": d['asin'],
                         "img": d['img']} for d in v] for k, v in age_groups.items()}
}

# Print summary
age_order = ["2+", "3+", "4+", "5+", "6+", "7+", "Allgemein"]
for age in age_order:
    if age in age_groups:
        games = age_groups[age]
        print(f"\n{age}: {len(games)} Spiele")
        for g in games:
            print(f"  -{g['pct']}% | {g['price']}€ (UVP {g['uvp']}€) | {g['asin']} | {g['title'][:80]}")

json.dump(output, open("/tmp/kinderspiele_data.json", "w"), ensure_ascii=False, indent=2)
print(f"\nTotal: {len(deals)} deals, {len(age_groups)} groups")
