import time,re,json,requests,io,random,subprocess
import numpy as np
from PIL import Image
from scipy import ndimage
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
BASE='http://ein38eu95792b.4656hd15.cc/geetest_page.html'
def mk():
    o=Options(); o.set_preference('dom.webdriver.enabled',False); o.set_preference('network.trr.mode',5)
    o.set_preference('network.proxy.type',0)
    o.set_preference('general.useragent.override','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0')
    return webdriver.Firefox(service=Service('./gd0371/geckodriver'), options=o)
def xdo(*a): subprocess.run(['xdotool',*map(str,a)],check=False)
def find_x(bg,sl,top):
    g=np.array(bg.convert('L')).astype(np.float32); sa=np.array(sl); full=sa[:,:,3]>128
    ys,xs=np.where(full); ax0,ay0=xs.min(),ys.min(); aw,ah=xs.max()-ax0+1,ys.max()-ay0+1
    am=full[ay0:ay0+ah,ax0:ax0+aw]; closed=ndimage.grey_closing(g,size=(61,61)); bh=closed-g; best=[]
    for th in [10,15,20,25,30,35,40,45,50]:
        lab,n=ndimage.label(bh>th)
        for i in range(1,n+1):
            yy,xx=np.where(lab==i); a=len(xx)
            if a<400: continue
            x0,x1,y0,y1=xx.min(),xx.max(),yy.min(),yy.max(); w=x1-x0+1; h=y1-y0+1
            if abs(w-aw)>20 or abs(h-ah)>20: continue
            cm=lab[y0:y1+1,x0:x1+1]==i; A=np.zeros_like(cm); hh=min(ah,cm.shape[0]); ww=min(aw,cm.shape[1]); A[:hh,:ww]=am[:hh,:ww]
            inter=(A&cm).sum(); union=(A|cm).sum(); iou=inter/union if union else 0
            best.append((iou,int(x0)-int(ax0),th))
    if not best: return 0,0
    iou,base,th=max(best); dark=g<th; bx=base; bi=0
    for dx in range(-6,7):
        x=base+dx
        if x<0 or x+ax0+aw>g.shape[1]: continue
        reg=dark[top:top+ah,x+ax0:x+ax0+aw]; i=(reg&am).sum(); u=(reg|am).sum(); v=i/u if u else 0
        if v>bi: bi=v; bx=x
    return iou,bx
def drag(D,X,Y):
    xdo('mousemove',X,Y); time.sleep(0.3); xdo('mousedown',1); time.sleep(0.2)
    pos=0; over=random.uniform(2,4)
    while pos<D+over:
        pos=min(D+over,pos+random.uniform(2,6)); xdo('mousemove',int(X+pos),Y+random.choice([0,0,0,1,-1])); time.sleep(random.uniform(0.015,0.04))
    time.sleep(0.1)
    while pos>D: pos-=random.choice([1,2]); xdo('mousemove',int(X+pos),Y); time.sleep(random.uniform(0.02,0.04))
    time.sleep(0.1); xdo('mouseup',1)
for load in range(1,3):
    if load>1: time.sleep(random.uniform(25,40))
    d=mk(); d.set_page_load_timeout(40)
    try:
        d.set_window_position(0,0); d.set_window_size(1000,820); d.get(BASE)
        ok=False
        for _ in range(60):
            time.sleep(0.5)
            if d.execute_script("return document.querySelectorAll('.geetest_bg').length>0"): ok=True; break
        if not ok: print('load',load,'no captcha (rate limited)'); d.quit(); continue
        for retry in range(1,4):
            time.sleep(0.8)
            info=d.execute_script("""function r(s){var e=document.querySelector(s);if(!e)return null;var b=e.getBoundingClientRect();return {t:b.top,l:b.left,w:b.width,h:b.height,bg:getComputedStyle(e).backgroundImage};}return {bg:r('.geetest_bg'),slice:r('.geetest_slice'),slicebg:r('.geetest_slice_bg'),btn:r('.geetest_btn'),sx:window.mozInnerScreenX,sy:window.mozInnerScreenY};""")
            if not info.get('bg'): print(' no bg'); break
            def dl(u):
                m=re.search(r'url\("?([^")]+)"?\)',u or '');return requests.get(m.group(1).replace('http://','https://'),timeout=20,verify=False).content
            bg=Image.open(io.BytesIO(dl(info['bg']['bg']))).convert('RGB'); sl=Image.open(io.BytesIO(dl(info['slicebg']['bg']))).convert('RGBA')
            top=int(round((info['slice']['t']-info['bg']['t'])*bg.size[1]/info['bg']['h'])); top=max(0,min(bg.size[1]-sl.size[1],top))
            iou,tl=find_x(bg,sl,top); initdx=info['slice']['l']-info['bg']['l']; scale=info['bg']['w']/bg.size[0]; D=max(0,tl-initdx)*scale
            print(f'load{load} retry{retry} IoU={iou:.3f} target={tl} initdx={initdx:.1f} D={D:.2f}')
            if iou<0.6: print(' low iou'); break
            X=int(info['sx']+info['btn']['l']+info['btn']['w']/2); Y=int(info['sy']+info['btn']['t']+info['btn']['h']/2)
            drag(D,X,Y); val=None
            for _ in range(16):
                time.sleep(0.5); val=d.execute_script('return window.validateResult')
                if val: break
            print('  validate',json.dumps(val,ensure_ascii=False) if val else None)
            if val:
                open('gt_result.json','w').write(json.dumps(val,ensure_ascii=False)); d.quit(); raise SystemExit
        d.quit()
    except SystemExit: break
    except Exception as ex:
        print('load',load,'ERR',str(ex)[:120])
        try:d.quit()
        except:pass
