#!/usr/bin/env python3
"""番茄小说下载器 Web 网关：静态前端 + WebSocket 协议 + Tauri IPC 桥"""
import base64, hashlib, json, os, glob, struct, threading, time, uuid
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
RDIR = '/tmp/fq_rpc'
QUEUE = os.path.join(RDIR, 'queue')
TOKEN = 'fq-local-session'
GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
LOGIN_PAGE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'login_page.html')

TIMEOUTS = {'default': 60, 'search': 130, 'book_detail': 130, 'chapter_content': 130,
            'import_local_epub': 310, 'import_local_txt': 310, 'webdav_test': 70}
LOG = open(os.path.join(RDIR, 'gateway.log'), 'a', buffering=1)

def log(*a): print(time.strftime('%H:%M:%S'), *a, file=LOG)

def enqueue(action, payload, detached=False):
    rid = uuid.uuid4().hex[:12]
    tmp = os.path.join(RDIR, 'task_%s.part' % rid)
    final = os.path.join(RDIR, 'task_%s.json' % rid)
    rec = {'action': action, 'payload': payload or {}}
    if detached: rec['detached'] = True
    with open(tmp, 'w', encoding='utf-8') as f:
        json.dump(rec, f, ensure_ascii=False)
    os.rename(tmp, final)          # 原子发布，C 侧只认 .json 结尾
    return rid

def drop_task(rid):
    try: os.unlink(os.path.join(RDIR, 'task_%s.json' % rid))
    except OSError: pass

def wait_result(rid, timeout):
    path = os.path.join(RDIR, 'result_%s.json' % rid)
    end = time.time() + timeout
    while time.time() < end:
        if os.path.exists(path):
            try:
                with open(path, encoding='utf-8') as f:
                    data = json.load(f)
                os.unlink(path)
                return data
            except Exception:
                pass
        time.sleep(0.05)
    drop_task(rid)
    return {'ok': False, 'error': {'message': '网等候后端超时', 'status': 504}}

class WS:
    def __init__(self, handler):
        self.h = handler
        self.rfile = handler.rfile
        self.wfile = handler.wfile
        self.lock = threading.Lock()

    def handshake(self):
        key = self.h.headers.get('Sec-WebSocket-Key', '')
        acc = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode()
        self.h.send_response(101, 'Switching Protocols')
        self.h.send_header('Upgrade', 'websocket')
        self.h.send_header('Connection', 'Upgrade')
        self.h.send_header('Sec-WebSocket-Accept', acc)
        self.h.end_headers()

    def recv(self):
        b = self.rfile.read(2)
        if len(b) < 2: return None
        b1, b2 = b[0], b[1]
        op = b1 & 0x0F
        masked = b2 & 0x80
        ln = b2 & 0x7F
        if ln == 126:
            ln = struct.unpack('>H', self.rfile.read(2))[0]
        elif ln == 127:
            ln = struct.unpack('>Q', self.rfile.read(8))[0]
        mask = self.rfile.read(4) if masked else b'\x00' * 4
        data = self.rfile.read(ln) if ln else b''
        if masked:
            data = bytes(c ^ mask[i % 4] for i, c in enumerate(data))
        if op == 0x8: return None
        if op == 0x9:
            self.send(data, 0xA); return self.recv()
        if op == 0xA: return self.recv()
        return data

    def send(self, data, op=0x1):
        if isinstance(data, str): data = data.encode()
        n = len(data)
        hdr = bytes([0x80 | op])
        if n < 126: hdr += bytes([n])
        elif n < 65536: hdr += bytes([126]) + struct.pack('>H', n)
        else: hdr += bytes([127]) + struct.pack('>Q', n)
        with self.lock:
            self.wfile.write(hdr + data); self.wfile.flush()

class H(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
    def log_message(self, *a): pass

    def do_GET(self):
        u = urlparse(self.path)
        if u.path == '/ws': return self.handle_ws()
        if u.path == '/login': return self.send_login_page()
        if u.path == '/login-snap.png': return self.send_login_snap()
        if u.path == '/login-status':
            rid = enqueue('bootstrap', {})
            res = wait_result(rid, 30)
            acc = ((res.get('payload') or {}).get('account') or {}) if res.get('ok') else {}
            return self.send_json({'ok': True, 'payload': acc or {'status': 'unknown'}})
        if u.path == '/login-click':
            return self.login_cmd('click')
        if u.path == '/healthz':
            return self.send_json({'ok': True, 'queue': os.path.exists(QUEUE)})
        rel = 'index.html' if u.path in ('/', '') else u.path.lstrip('/')
        path = os.path.normpath(os.path.join(STATIC, rel))
        if not path.startswith(STATIC) or not os.path.isfile(path):
            return self.send_json({'error': 'not found'}, 404)
        ext = os.path.splitext(path)[1].lower()
        ctype = {'.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8',
                 '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8',
                 '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon'}.get(ext, 'application/octet-stream')
        with open(path, 'rb') as f: body = f.read()
        self.send_response(200)
        self.send_header('Content-Type', ctype)
        self.send_header('Content-Length', str(len(body)))
        self.send_header('Cache-Control', 'no-store')
        self.end_headers()
        self.wfile.write(body)

    def send_json(self, obj, code=200):
        body = json.dumps(obj, ensure_ascii=False).encode()
        self.send_response(code)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def send_login_page(self):
        try:
            html = open(LOGIN_PAGE, 'rb').read()
        except OSError:
            return self.send_json({'error': 'login page missing'}, 500)
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.send_header('Content-Length', str(len(html)))
        self.end_headers()
        self.wfile.write(html)

    def send_login_snap(self):
        png = '/tmp/fq_rpc/snap.png'
        try: os.unlink(png)
        except OSError: pass
        open('/tmp/fq_rpc/snap.req', 'w').close()
        for _ in range(80):
            if os.path.exists(png):
                try:
                    data = open(png, 'rb').read()
                    if data[:4] == b'\x89PNG' and b'IEND' in data[-32:]:
                        self.send_response(200)
                        self.send_header('Content-Type', 'image/png')
                        self.send_header('Content-Length', str(len(data)))
                        self.send_header('Cache-Control', 'no-store')
                        self.end_headers(); self.wfile.write(data); return
                except OSError: pass
            time.sleep(0.1)
        self.send_json({'error': 'snapshot timeout'}, 504)

    def login_cmd(self, kind, data=None):
        data = data or {}
        js = None
        if kind == 'click':
            x = int(data.get('x') or 0); y = int(data.get('y') or 0)
            js = ("(function(){var e=document.elementFromPoint(%d,%d);if(!e)return 'none';"
                  "try{e.focus()}catch(_){};try{e.click()}catch(_){};return e.tagName})()" % (x, y))
        elif kind == 'type':
            txt = json.dumps(str(data.get('text') or ''), ensure_ascii=False)
            js = ("(function(){var e=document.activeElement;if(!e)return 'no-focus';"
                  "if(e.value===undefined)return 'not-input';"
                  "var s=e.value||'';e.value=s+%s;"
                  "e.dispatchEvent(new Event('input',{bubbles:true}));"
                  "e.dispatchEvent(new Event('change',{bubbles:true}));return e.tagName})()" % txt)
        elif kind == 'key':
            k = json.dumps(str(data.get('key') or 'Enter'))
            js = ("(function(){var e=document.activeElement;if(!e)return 'no-focus';"
                  "['keydown','keyup'].forEach(function(t){e.dispatchEvent(new KeyboardEvent(t,{key:%s,bubbles:true}))});"
                  "if(%s==='Enter'){try{e.form&&e.form.requestSubmit&&e.form.requestSubmit()}catch(_){}}return e.tagName})()" % (k, k))
        elif kind == 'tab':
            want = str(data.get('name') or 'qrcode')
            keyword = '扫码登录' if want == 'qrcode' else '验证码登录'
            kw = json.dumps(keyword, ensure_ascii=False)
            js = ("(function(){var ks=%s;var all=document.querySelectorAll('div,span,a,button,li');"
                  "for(var i=0;i<all.length;i++){var t=(all[i].textContent||'').trim();"
                  "if(t===ks){try{all[i].click();return 'clicked'}catch(_){}}}return 'not-found'})()" % kw)
        else:
            return self.send_json({'error': 'bad cmd'}, 400)
        open('/tmp/fq_rpc/loginjs.txt', 'w', encoding='utf-8').write(js)
        time.sleep(0.45)
        self.send_json({'ok': True, 'cmd': kind})

    def do_POST(self):
        u = urlparse(self.path)
        n = int(self.headers.get('content-length') or 0)
        try: data = json.loads(self.rfile.read(n) or b'{}')
        except Exception: data = {}
        if u.path in ('/login-click', '/login-type', '/login-key', '/login-tab'):
            return self.login_cmd(u.path.lstrip('/').replace('login-',''), data)
        if u.path == '/rpc':
            action = data.get('action'); payload = data.get('payload') or {}
            if action == 'account_login':
                enqueue('account_login', payload, detached=True)
                return self.send_json({'ok': True, 'payload': {'status': 'logging_in'}})
            rid = enqueue(action, payload)
            res = wait_result(rid, float(data.get('timeout') or TIMEOUTS.get(action, TIMEOUTS['default'])))
            return self.send_json(res)
        self.send_json({'error': 'not found'}, 404)

    def handle_ws(self):
        q = parse_qs(urlparse(self.path).query)
        sess = (q.get('session') or [''])[0]
        if TOKEN and sess != TOKEN:
            self.send_json({'error': 'bad session'}, 403); return
        ws = WS(self)
        try: ws.handshake()
        except Exception: return
        log('ws open', sess)
        try:
            while True:
                raw = ws.recv()
                if raw is None: break
                try: msg = json.loads(raw)
                except Exception: continue
                if msg.get('type') != 'request': continue
                rid = str(msg.get('id'))
                action = msg.get('action'); payload = msg.get('payload') or {}
                threading.Thread(target=self._work, args=(ws, rid, action, payload), daemon=True).start()
        except Exception as e:
            log('ws err', repr(e))
        log('ws closed')

    def _work(self, ws, rid, action, payload):
        t0 = time.time()
        if action == 'account_login':
            enqueue('account_login', payload, detached=True)
            try: ws.send(json.dumps({'type':'response','id':rid,'ok':True,'payload':{'status':'logging_in'}}))
            except Exception: pass
            log('rpc account_login fired (detached)')
            return
        backend_id = enqueue(action, payload)
        res = wait_result(backend_id, TIMEOUTS.get(action, TIMEOUTS['default']))
        msg = {'type': 'response', 'id': rid, 'ok': bool(res.get('ok'))}
        if res.get('ok'): msg['payload'] = res.get('payload')
        else: msg['error'] = res.get('error') or {'message': '未知错误'}
        try: ws.send(json.dumps(msg, ensure_ascii=False))
        except Exception as e: log('send fail', repr(e))
        log('rpc', action, 'ok' if msg['ok'] else 'ERR', '%.2fs' % (time.time() - t0))

if __name__ == '__main__':
    os.makedirs(RDIR, exist_ok=True)
    port = int(os.environ.get('PORT', '18426'))
    log('gateway on', port, 'static', STATIC)
    ThreadingHTTPServer(('0.0.0.0', port), H).serve_forever()
