#!/usr/bin/env python3
# PRESALE-JAGD: bf.st Thread-Suche nach ICO-/Presale-/IDO-Listen
import subprocess, time, re, json, os, html

COOKIE = os.path.expanduser('~/.hermes/cache/scratch/bfst/cookies.txt')
OUT = os.path.expanduser('~/investoren-daten/presale/bfst_presale_threads.json')

KEYWORDS = ['presale', 'ico', 'ido', 'ieo', 'token sale', 'launchpad',
            'pinksale', 'coinlist', 'ico investors', 'ico database',
            'crypto investors list', 'ico users', 'token investors']

def post_search(kw):
    p = subprocess.run(['curl', '-s', '-m', '60', '--socks5-hostname', '127.0.0.1:40000',
                        '-b', COOKIE, '-c', COOKIE, '-A', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                        '-D', '-',
                        '-X', 'POST', 'https://bf.st/search.php', '--data',
                        f'action=do_search&keywords={kw.replace(" ", "+")}&postthread=1&showresults=threads&submit=Search'],
                       capture_output=True, text=True)
    loc = ''
    for line in p.stdout.splitlines()[:40]:
        if line.lower().startswith('location:'):
            loc = line.split(':', 1)[1].strip()
            break
    return loc, p.stdout

def get(url):
    return subprocess.run(['curl', '-s', '-m', '60', '--socks5-hostname', '127.0.0.1:40000',
                          '-b', COOKIE, '-A', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', url],
                         capture_output=True, text=True).stdout

threads = json.load(open(OUT)) if os.path.exists(OUT) else {}
done_kws = threads.get('_done_kws', [])

for kw in KEYWORDS:
    if kw in done_kws:
        continue
    loc = ''
    for attempt in range(6):
        loc, body = post_search(kw)
        if loc:
            break
        m = re.search(r'wait another (\d+) seconds', body)
        wait = int(m.group(1)) + 3 if m else 33
        print(f'{kw}: flood, warte {wait}s', flush=True)
        time.sleep(wait)
    if not loc:
        print(f'{kw}: GESCHEITERT', flush=True)
        continue
    body = get(loc)
    found = {}
    for m in re.finditer(r'<a href="(https://bf\.st/(Thread-[A-Za-z0-9\-]+))"[^>]*>([^<]+)</a>', body):
        url, slug, title = m.group(1), m.group(2), html.unescape(m.group(3)).strip()
        found[slug] = {'url': url, 'title': title, 'kw': kw}
    if not found:
        for m in re.finditer(r'(Thread-[A-Za-z0-9\-]+)', body):
            found.setdefault(m.group(1), {'url': 'https://bf.st/' + m.group(1), 'title': '?', 'kw': kw})
    for slug, info in found.items():
        threads.setdefault(slug, info)
    done_kws.append(kw)
    threads['_done_kws'] = done_kws
    json.dump(threads, open(OUT, 'w'), indent=1, ensure_ascii=False)
    print(f'{kw}: {len(found)} Threads', flush=True)
    time.sleep(33)
print('FERTIG', len([k for k in threads if not k.startswith('_')]), flush=True)
