#!/usr/bin/python3
import subprocess, time, re, json, os
COOKIE = os.path.expanduser('~/.hermes/cache/scratch/bfst/cookies.txt')
OUT = 'bfst_dt_threads.json'
KEYWORDS = ['tradingview','myfxbook','forexfactory','mql5','zulutrade','pocket option',
            'iqoption','binomo','ftmo','prop firm','trading course','day trading','trader database','traders list']
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 {}
for kw in KEYWORDS:
    if kw in [v.get('kw') for v in threads.values()]: print(kw,'done',flush=True); continue
    loc=''
    for attempt in range(5):
        loc, body = post_search(kw)
        if loc: break
        m=re.search(r'wait another (\d+) seconds',body)
        w=int(m.group(1))+3 if m else 33
        print(f'{kw}: flood {w}s',flush=True); time.sleep(w)
    if not loc: print(kw,'FAIL',flush=True); continue
    body=get(loc)
    found=set(re.findall(r'(Thread-[A-Za-z0-9\-]+)',body))
    for l in found:
        if l not in threads: threads[l]={'kw':kw}
    print(f'{kw}: {len(found)} threads',flush=True)
    json.dump(threads,open(OUT,'w'),indent=1)
print('FERTIG', len(threads))
