# -*- coding: utf-8 -*-
"""鼎綸 授權書套印 · 本機抓取小幫手
宏泰官網 (www.hontai.com.tw) 只接受台灣 IP，會擋 Cloudflare/雲端代理。
這支小幫手在你的台灣電腦上跑，代抓宏泰/安聯授權書 PDF，讓瀏覽器裡的
授權書套印中心 (https://rex1688.com/rex/auth/) 能一鍵「自動抓取」。

用法：雙擊 start-helper.bat，或執行  python authz_helper.py
之後在授權書套印中心點「🔄 自動抓取」即可。關掉視窗即停止。
只回應本機 (127.0.0.1) 的請求，只放行 rex1688.com 呼叫，不對外開放。
"""
import http.server, socketserver, urllib.request, urllib.parse, json, sys
try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")  # 避免 Windows cp950 主控台編碼崩潰
except Exception:
    pass

PORT = 8788
ALLOW_ORIGIN = "https://rex1688.com"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"

def fetch_hontai():
    req = urllib.request.Request(
        "https://www.hontai.com.tw/Policyforms/htf/Form_PPAuthorized.aspx",
        headers={"User-Agent": UA, "Accept": "application/pdf,*/*"})
    with urllib.request.urlopen(req, timeout=40) as r:  # urllib follows the 302 to the PDF
        return r.read(), r.headers.get("Content-Type", "")

def fetch_allianz():
    base = "https://es.allianz.com.tw/customer/companyInfo/FileDownload"
    ref = base + "/GetDocFile.aspx?type=A02&PageCnt=1"
    doc_id = "Fm00010571"
    try:
        with urllib.request.urlopen(urllib.request.Request(ref, headers={"User-Agent": UA}), timeout=30) as g:
            import re
            m = re.search(rb"Fm\d+", g.read())
            if m:
                doc_id = m.group(0).decode()
    except Exception:
        pass
    body = urllib.parse.urlencode({"DocId": doc_id, "DocName": "", "Cnt": 1}).encode()
    req = urllib.request.Request(base + "/DownloadFile.aspx", data=body,
        headers={"User-Agent": UA, "Referer": ref,
                 "Content-Type": "application/x-www-form-urlencoded"})
    with urllib.request.urlopen(req, timeout=40) as r:
        return r.read(), r.headers.get("Content-Type", "")

SOURCES = {"hontai": fetch_hontai, "allianz": fetch_allianz}

class H(http.server.BaseHTTPRequestHandler):
    def _cors(self):
        self.send_header("Access-Control-Allow-Origin", ALLOW_ORIGIN)
        self.send_header("Access-Control-Allow-Private-Network", "true")  # Chrome PNA
        self.send_header("Vary", "Origin")

    def do_OPTIONS(self):
        self.send_response(204)
        self._cors()
        self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "*")
        self.send_header("Access-Control-Max-Age", "86400")
        self.end_headers()

    def _json(self, code, obj):
        b = json.dumps(obj).encode()
        self.send_response(code); self._cors()
        self.send_header("Content-Type", "application/json"); self.end_headers()
        self.wfile.write(b)

    def do_GET(self):
        u = urllib.parse.urlparse(self.path)
        if u.path == "/ping":
            return self._json(200, {"ok": True, "helper": "authz", "port": PORT})
        if u.path != "/authz":
            return self._json(404, {"error": "not found"})
        co = urllib.parse.parse_qs(u.query).get("co", [""])[0].lower()
        fn = SOURCES.get(co)
        if not fn:
            return self._json(400, {"error": "unknown co", "allow": list(SOURCES)})
        try:
            data, ct = fn()
            if b"%PDF" not in data[:1024] or len(data) < 1024:
                return self._json(502, {"error": "upstream not PDF", "bytes": len(data), "ct": ct})
            self.send_response(200); self._cors()
            self.send_header("Content-Type", "application/pdf")
            self.send_header("Content-Disposition", 'inline; filename="%s.pdf"' % co)
            self.send_header("Content-Length", str(len(data))); self.end_headers()
            self.wfile.write(data)
        except Exception as e:
            self._json(502, {"error": "fetch failed", "detail": str(e)})

    def log_message(self, *a):
        pass  # 安靜

if __name__ == "__main__":
    print("=" * 52)
    print(" 鼎綸 授權書抓取小幫手 已啟動")
    print(" 監聽 http://127.0.0.1:%d  (只服務本機)" % PORT)
    print(" 現在可到授權書套印中心點「自動抓取」")
    print(" 關閉此視窗即停止。")
    print("=" * 52)
    with socketserver.ThreadingTCPServer(("127.0.0.1", PORT), H) as httpd:
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n已停止。")
