#!/usr/bin/env python3
# Korrigierte Broker-Website-Extraktion aus forex-ratings.com + earnforex.com (cached oder live)
import re, time, random, urllib.request as ur, json, os
BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0"}

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

# --- forex-ratings: alle JSON-LD urls, nicht-forex-ratings nehmen ---
out_fr = {}
if os.path.exists(BASE + "/fr_pages_cache"):
    import pickle
    pages = pickle.load(open(BASE + "/fr_pages_cache", "rb"))
else:
    pages = {}
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/"]
print(len(urls), "fr pages", flush=True)
for i, u in enumerate(urls):
    if u not in pages:
        try:
            pages[u] = fetch("https://www.forex-ratings.com" + u)
        except Exception:
            pages[u] = ""
    m = re.findall(r'"url":\s*"(https?://[^"]+)"', pages[u])
    site = next((x for x in m if "forex-ratings.com" not in x and "forex-ratings" not in x), None)
    if site:
        out_fr[u] = site
    if i % 50 == 0:
        json.dump(out_fr, open(BASE + "/fr_broker_sites2.json", "w"))
        print(i, len(out_fr), flush=True)
    time.sleep(random.uniform(0.35, 0.7))
json.dump(out_fr, open(BASE + "/fr_broker_sites2.json", "w"))
print("FR DONE", len(out_fr), flush=True)

# --- earnforex: broker profile link ---
urls2 = sorted(set(re.findall(r'href="(/forex-brokers/[^"/]+/)"', open(BASE + "/ef_dir.html").read())))
urls2 = [u for u in urls2 if u != "/forex-brokers/"]
out_ef = {}
ef_pages = {}
print(len(urls2), "ef pages", flush=True)
for i, u in enumerate(urls2):
    try:
        html = fetch("https://www.earnforex.com" + u)
    except Exception:
        html = ""
    m = re.search(r'broker profile:</span>\s*<a href="(https?://[^"]+)"', html)
    if not m:
        m = re.search(r'href="(https?://[^"]+)"[^>]*target="_blank" rel="nofollow">', html)
    if m and "earnforex" not in m.group(1):
        out_ef[u] = m.group(1)
    if i % 40 == 0:
        json.dump(out_ef, open(BASE + "/ef_broker_sites2.json", "w"))
        print(i, len(out_ef), flush=True)
    time.sleep(random.uniform(0.4, 0.8))
json.dump(out_ef, open(BASE + "/ef_broker_sites2.json", "w"))
print("EF DONE", len(out_ef), flush=True)
