#!/usr/bin/env python3
"""BSN Article QC Checker — auto-fix umlauts, flag forbidden words & missing affiliate links.
QUICK CHECK: python3 qc_check.py <article.html>
FULL WORKFLOW: Use korrekturschleife skill (Writer → Fact-Checker → Korrektur)
"""
import sys, re

UMLAUT_FIXES = {
    'uber ': 'über ', ' uber ': ' über ', 'fur ': 'für ', ' fur ': ' für ',
    'Fur ': 'Für ', 'fuhrt ': 'führt ', 'Mazene': 'Mäzene', 'duster': 'düster',
    'kunstlich': 'künstlich', 'Anderung': 'Änderung', 'Verfugbarkeit': 'Verfügbarkeit',
    'berucksichtigt': 'berücksichtigt', 'Berucksichtigt': 'Berücksichtigt',
    'eingeschrankt': 'eingeschränkt', 'Außergewohnliches': 'Außergewöhnliches',
}

FORBIDDEN = ['XML API', 'API v2', 'xmlapi2', 'Betriebsgeheimnis', 
             'FlareSolverr', 'Scraping', 'Proxy', 'Cronjob']

LOGIC_FIXES = {
    'Nicht-Basisspielen': 'Basisspielen',
}

def main():
    if len(sys.argv) < 2:
        print("Usage: qc_check.py <article.html>")
        sys.exit(1)
    
    path = sys.argv[1]
    with open(path) as f:
        html = f.read()
    
    fixes = []
    errors = []
    
    # 1. Auto-fix umlauts
    for wrong, correct in UMLAUT_FIXES.items():
        if wrong in html:
            count = html.count(wrong)
            html = html.replace(wrong, correct)
            fixes.append(f'  UMLAUT: {wrong} → {correct} ({count}x)')
    
    # 2. Auto-fix logic errors
    for wrong, correct in LOGIC_FIXES.items():
        if wrong in html:
            html = html.replace(wrong, correct)
            fixes.append(f'  LOGIK: {wrong} → {correct}')
    
    # 3. Flag forbidden words (manual fix needed)
    for word in FORBIDDEN:
        if word.lower() in html.lower():
            errors.append(f'  VERBOTEN: "{word}" im Artikel!')
    
    # 4. Check deal/buy links (NOT Quellen) for affiliate tracking
    # Deal links: inside .buy-link, infobox, or table td.buy
    deal_sections = re.findall(r'(?:class="buy-link"|class="infobox"|Zum Deal).*?</a>', html, re.DOTALL)
    for section in deal_sections:
        links = re.findall(r'href="([^"]*milan-spiele\.de[^"]*)"', section)
        for link in links:
            if 'awinmid' not in link:
                errors.append(f'  AFFILIATE: Milan-Link ohne AWIN: {link[:80]}')
    
    # Report
    if fixes:
        print(f'QC: {path}')
        for f in fixes:
            print(f)
        print(f'  → {len(fixes)} Fixes angewendet.')
    
    if errors:
        for e in errors:
            print(e)
        print(f'\n  FEHLER: {len(errors)} manuelle Korrekturen notig!')
        sys.exit(1)
    
    if not fixes and not errors:
        print(f'QC: {path} — OK')
    
    if fixes:
        with open(path, 'w') as f:
            f.write(html)
    
    sys.exit(0)

if __name__ == '__main__':
    main()
