#!/usr/bin/env python3
# LeakRadar-Unlocks für Krypto-Quellen (Punkte-Budget: Tageskontingent 10.000)
# Zahlung: 1 Punkt/Record. Restart-fähig: bereits geholte Domains in lr_done.json
import json, os, time, subprocess, sys

CD = os.path.expanduser('~/krypto-angriff')
TOKEN = open(os.path.expanduser('~/.secrets/leakradar_paid_token.txt')).read().strip()
OUT = CD + '/lr_unlocks'
DONE = CD + '/lr_done.json'
os.makedirs(OUT, exist_ok=True)

# (domain, kategorie, max_unlock) — Gesamtbudget <= 9800
PLAN = [
    ('coinmarketcap.com', 'krypto-portal', 3300),
    ('coinpayments.net', 'payment-anbieter', 2500),
    ('coingate.com', 'payment-anbieter', 1500),
    ('fixedfloat.com', 'payment-anbieter', 800),
    ('exolix.com', 'payment-anbieter', 868),
    ('coinremitter.com', 'payment-anbieter', 685),
    ('stealthex.io', 'payment-anbieter', 255),
    ('btc-echo.de', 'krypto-magazin', 271),
    ('krypto-magazin.de', 'krypto-magazin', 92),
    ('cryptonomist.ch', 'krypto-magazin', 2),
]

done = json.load(open(DONE)) if os.path.exists(DONE) else {}

def unlock(domain, mx):
    fn = f'{OUT}/{domain.replace(".", "_")}.json'
    url = f'https://api.leakradar.io/search/domain/{domain}/customers/unlock?is_email=true&max={mx}'
    for att in range(4):
        p = subprocess.run(['curl', '-s', '-m', '300', '-X', 'POST', url,
                            '-H', 'Authorization: Bearer ' + TOKEN,
                            '-o', fn, '-w', '%{http_code}'], capture_output=True, text=True)
        code = p.stdout.strip()
        if code == '200':
            return fn, code
        body = open(fn).read()[:200] if os.path.exists(fn) else ''
        print(domain, 'HTTP', code, body, flush=True)
        if 'Insufficient points' in body:
            return None, code
        time.sleep(10)
    return None, code

for domain, kat, mx in PLAN:
    if domain in done:
        print('skip', domain, flush=True)
        continue
    fn, code = unlock(domain, mx)
    if fn:
        try:
            d = json.load(open(fn))
            n = len(d) if isinstance(d, list) else len(d.get('items', d.get('data', [])))
        except Exception:
            n = -1
        done[domain] = {'records': n, 'file': fn}
        json.dump(done, open(DONE, 'w'), indent=1)
        print('OK', domain, n, flush=True)
    else:
        print('FAIL', domain, code, flush=True)
        if code == '402' or code == '400':
            break
    time.sleep(3)
print('DONE', json.dumps(done), flush=True)
