#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""江苏环评网 js-eia.cn 微信扫码登录 — 获取登录 cookie 存盘
用法: python3 jseia_scan_login.py [输出cookie文件]
流程: 请求 qrcode → 下载二维码图片 → 轮询 check 直到登录成功 → 保存 cookie
"""
import sys, os, json, time, urllib.request, urllib.error, http.cookiejar

BASE = "https://www.js-eia.cn"
OUT = sys.argv[1] if len(sys.argv) > 1 else "/root/gov_crawler/jseia_cookie.txt"
QR_IMG = sys.argv[2] if len(sys.argv) > 2 else "/tmp/jseia_qrcode.png"

cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
opener.addheaders = [
    ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"),
    ("Accept", "application/json, text/javascript, */*; q=0.01"),
    ("Referer", BASE + "/guide"),
    ("X-Requested-With", "XMLHttpRequest"),
]


def post_json(path, data=None):
    url = BASE + path
    body = urllib.parse.urlencode(data or {}).encode() if data else b""
    req = urllib.request.Request(url, data=body, method="POST")
    try:
        resp = opener.open(req, timeout=20)
        return json.loads(resp.read().decode("utf-8", errors="ignore"))
    except urllib.error.HTTPError as e:
        return {"code": -1, "msg": f"HTTP {e.code}"}
    except Exception as e:
        return {"code": -1, "msg": str(e)}


def get_json(path):
    url = BASE + path
    try:
        resp = opener.open(url, timeout=20)
        return resp.read().decode("utf-8", errors="ignore")
    except Exception as e:
        return f"ERR {e}"


if __name__ == "__main__":
    import urllib.parse

    print("[1] 获取二维码...", flush=True)
    r = post_json("/wechatlg/qrcode/")
    if r.get("code") != 0:
        print(f"[FAIL] {r}", flush=True)
        sys.exit(1)
    token = r["data"]["token"]
    qr_url = r["data"]["qrcode_url"]
    print(f"[OK] token={token[:12]}...", flush=True)
    print(f"[2] 下载二维码图片: {qr_url[:60]}...", flush=True)
    try:
        req = urllib.request.Request(qr_url, headers={"User-Agent": "Mozilla/5.0"})
        img = urllib.request.urlopen(req, timeout=30).read()
        with open(QR_IMG, "wb") as f:
            f.write(img)
        print(f"[OK] 二维码已保存 {QR_IMG} ({len(img)} bytes)", flush=True)
    except Exception as e:
        print(f"[WARN] 二维码下载失败: {e}", flush=True)

    print("[3] 等待扫码 (每2秒轮询, 最多300秒)...", flush=True)
    deadline = time.time() + 300
    logged_in = False
    while time.time() < deadline:
        time.sleep(2)
        res = get_json(f"/wechatlg/check?token={token}")
        # 返回可能是 {"index":100} (成功) / {"index":0} (超时) / {"index":1} (未扫) / "0" (token失效)
        idx = None
        if isinstance(res, str):
            s = res.strip()
            if s.startswith("{"):
                try:
                    idx = json.loads(s).get("index")
                except Exception:
                    pass
            elif s.isdigit():
                idx = int(s)
        if idx == 100:
            print("[SUCCESS] 登录成功!", flush=True)
            logged_in = True
            break
        elif idx == 0:
            print("[TIMEOUT] 二维码已过期, 请重跑脚本", flush=True)
            sys.exit(2)
        else:
            print(f"[WAIT] 等待扫码... ({res[:60]})", flush=True)

    if not logged_in:
        print("[FAIL] 未检测到登录", flush=True)
        sys.exit(3)

    # 登录成功: 访问首页确认 session
    print("[4] 验证登录态...", flush=True)
    try:
        resp = opener.open(BASE + "/index.php?proid=011e345dac9494f5869e919104424c03", timeout=20)
        body = resp.read().decode("utf-8", errors="replace")
        final = resp.url
        print(f"[OK] HTTP {resp.status} final={final[:60]} len={len(body)}", flush=True)
        if "登录须知" in body:
            print("[WARN] 仍是登录页?", flush=True)
    except Exception as e:
        print(f"[WARN] 验证请求: {e}", flush=True)

    # 保存 cookie (Netscape 格式 + name=value 行)
    lines = ["# Netscape HTTP Cookie File"]
    pairs = []
    for c in cj:
        domain = c.domain if c.domain.startswith(".") else "." + c.domain
        flag = "TRUE" if c.domain.startswith(".") else "FALSE"
        lines.append(f"{domain}\t{flag}\t{c.path}\t{'TRUE' if c.secure else 'FALSE'}\t{int(c.expires) if c.expires else 0}\t{c.name}\t{c.value}")
        pairs.append(f"{c.name}={c.value}")
    with open(OUT, "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")
        f.write("\n".join(pairs) + "\n")
    print(f"[OK] cookie 已保存: {OUT} ({len(pairs)} 个)", flush=True)
    print("[DONE]", flush=True)
