#!/usr/bin/env python3
# Fix: korrekte Broker-Websites aus earnforex (broker__grid-broker-name) + forex-ratings (itemReviewed.url)
import re, time, random, urllib.request as ur, urllib.error, json, os
BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"}
OUT = BASE + "/broker_sites_fixed.json"

def fetch(url, timeout=25):
    req = ur.Request(url, headers=UA)
    return ur.urlopen(req, timeout=timeout).read().decode("utf-8", "replace")

def dom(url):
    m = re.match(r'https?://([^/]+)', url)
    if not m: return None
    d = m.group(1).lower()
    d = re.sub(r'^www\.', '', d)
    return d

results = {}
if os.path.exists(OUT):
    results = json.load(open(OUT))

# --- earnforex ---
urls = sorted(set(re.findall(r'href="(/forex-brokers/[^"/]+/)"', open(BASE + "/ef_dir.html").read())))
urls = [u for u in urls if u != "/forex-brokers/"]
todo = [u for u in urls if "ef:" + u not in results]
print(len(urls), "ef pages,", len(todo), "todo", flush=True)
for i, u in enumerate(todo):
    site = None
    try:
        html = fetch("https://www.earnforex.com" + u)
        m = re.search(r'href="(https?://[^"]+)"[^>]*class="broker__grid-broker-name"', html)
        if not m:
            m = re.search(r'class="broker__grid-broker-name"[^>]*href="(https?://[^"]+)"', html)
        if not m:
            # Fallback: erster external nofollow-link ohne earnforex/social
            for cand in re.findall(r'href="(https?://[^"]+)"[^>]*rel="nofollow"', html):
                d = dom(cand)
                if d and 'earnforex' not in d and not re.search(r'(x|facebook|twitter|instagram|youtube|linkedin|pinterest|t\.me|vk)\.com$', d):
                    site = cand
                    break
        else:
            site = m.group(1)
    except Exception:
        pass
    results["ef:" + u] = site
    if i % 40 == 0:
        json.dump(results, open(OUT, "w")); print("ef", i, sum(1 for k, v in results.items() if k.startswith("ef:") and v), flush=True)
    time.sleep(random.uniform(0.4, 0.8))
json.dump(results, open(OUT, "w"))
print("EF DONE", sum(1 for k, v in results.items() if k.startswith("ef:") and v), flush=True)

# --- forex-ratings ---
urls = sorted(set(re.findall(r'href="(/forex-brokers/[^"/]+/)"', open(BASE + "/fr_dir.html").read())))
urls = [u for u in urls if u != "/forex-brokers/"]
todo = [u for u in urls if "fr:" + u not in results]
print(len(urls), "fr pages,", len(todo), "todo", flush=True)
for i, u in enumerate(todo):
    site = None
    try:
        html = fetch("https://www.forex-ratings.com" + u)
        # itemReviewed Organization url bevorzugen, sonst erste Nicht-eigene url
        m = re.search(r'"itemReviewed":\s*\{[^}]*?"url":\s*"(https?://[^"]+)"', html)
        if m:
            site = m.group(1)
        else:
            for cand in re.findall(r'"url":\s*"(https?://[^"]+)"', html):
                d = dom(cand)
                if d and 'forex-ratings' not in d:
                    site = cand
                    break
    except Exception:
        pass
    results["fr:" + u] = site
    if i % 40 == 0:
        json.dump(results, open(OUT, "w")); print("fr", i, sum(1 for k, v in results.items() if k.startswith("fr:") and v), flush=True)
    time.sleep(random.uniform(0.4, 0.8))
json.dump(results, open(OUT, "w"))
print("FR DONE", sum(1 for k, v in results.items() if k.startswith("fr:") and v), flush=True)
print("ALL DONE", flush=True)
