#!/usr/bin/env python3
# bf.st-Frischsuche: neue Keywords (Broker/Trading-Begriffe), Flood-Control
import subprocess, time, re, json, os

COOKIE = os.path.expanduser('~/.hermes/cache/scratch/bfst/cookies.txt')
OUT = os.path.expanduser('~/.hermes/cache/scratch/forex/bfst_forex_threads2.json')

KEYWORDS = ['fxcm', 'ic markets', 'exness', 'octafx', 'roboforex', 'metatrader',
            'trading signal', 'telegram trading']

OLD = os.path.expanduser('~/.hermes/cache/scratch/forex/bfst_forex_threads.json')
old_slugs = set(json.load(open(OLD)).keys()) if os.path.exists(OLD) else set()

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 = {}
if os.path.exists(OUT):
    threads = json.load(open(OUT))

for kw in KEYWORDS:
    if kw in [v.get('kw') for v in threads.values()]:
        print(kw, 'schon gesucht', flush=True)
        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 = re.findall(r'(Thread-[A-Za-z0-9\-]+)', body)
    neu = [l for l in set(found) if l not in old_slugs and l != 'Thread-']
    for l in set(found):
        if l not in threads:
            threads[l] = {'kw': kw, 'neu': l not in old_slugs}
    print(f'{kw}: {len(set(found))} Threads ({len(neu)} neu)', flush=True)
    json.dump(threads, open(OUT, 'w'), indent=1)
    time.sleep(34)

json.dump(threads, open(OUT, 'w'), indent=1)
print('TOTAL', len(threads))
