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'
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')
d=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
    while pos<D+3:
        pos=min(D+3,pos+random.uniform(2,6)); xdo('mousemove',int(X+pos),Y+random.choice([0,0,1,-1])); time.sleep(random.uniform(0.015,0.04))
    while pos>D: pos-=random.choice([1,2]); xdo('mousemove',int(X+pos),Y); time.sleep(0.02)
    xdo('mouseup',1)
try:
    d.set_window_position(0,0); d.set_window_size(1000,820); d.get(BASE)
    for _ in range(60):
        time.sleep(0.5)
        if d.execute_script("return document.querySelectorAll('.geetest_bg').length>0"): break
    time.sleep(1)
    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};""")
    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); scale=info['bg']['w']/bg.size[0]; D=tl*scale
    print('IoU',iou,'target',tl,'D',D)
    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); time.sleep(2)
    vurl=d.execute_script('return window.__vurl')
    print('vurl_len',len(vurl) if vurl else None)
    if vurl:
        u=vurl.replace('callback=geetest_','callback=cb')
        r=requests.get(u,timeout=20,verify=False)
        print('verify status',r.status_code,'len',len(r.text))
        print(r.text[:1500])
finally: d.quit()
