"""修 html983：把 Google jQuery 换成本地文件，并给 #spinner 加兜底隐藏。"""
from __future__ import annotations

import re
import sys
import urllib.request
from pathlib import Path

import pyzipper

import sys as _sys

NUM = _sys.argv[1] if len(_sys.argv) > 1 else "983"
ROOT = Path(rf"I:\phpstudy_pro\WWW\mubanceshi\html{NUM}")
PKG = Path(rf"I:\模板更新\pbootcms\html\html{NUM}")
PWD = b"www.yishuiwang.net"

FALLBACK = (
    "<script>document.addEventListener('DOMContentLoaded',function(){"
    "var s=document.getElementById('spinner');"
    "if(s){setTimeout(function(){s.classList.remove('show');},900);}});"
    "window.addEventListener('load',function(){var s=document.getElementById('spinner');"
    "if(s)s.classList.remove('show');});</script>"
)


def extract() -> None:
    if (ROOT / "index.html").is_file():
        print("本地已存在:", ROOT)
        return
    zips = sorted(PKG.glob("*.zip"))
    ROOT.mkdir(parents=True, exist_ok=True)
    with pyzipper.AESZipFile(zips[0]) as z:
        z.setpassword(PWD)
        z.extractall(ROOT)
    print("已解压:", zips[0].name)


def get_jquery() -> Path:
    dest = ROOT / "js" / "jquery-3.6.4.min.js"
    if dest.is_file() and dest.stat().st_size > 50000:
        print("jQuery 已存在:", dest.stat().st_size)
        return dest
    for url in ("https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js",
                "https://unpkg.com/jquery@3.6.4/dist/jquery.min.js"):
        try:
            with urllib.request.urlopen(url, timeout=40) as r:
                data = r.read()
            if len(data) > 50000:
                dest.write_bytes(data)
                print("jQuery 下载完成:", url, len(data))
                return dest
        except Exception as e:  # noqa: BLE001
            print("下载失败:", url, str(e)[:80])
    raise SystemExit("jQuery 下载失败")


def main() -> None:
    extract()
    jq = get_jquery()
    index = ROOT / "index.html"
    html = index.read_text(encoding="utf-8", errors="ignore")
    before = html
    html = re.sub(r'<script[^>]+ajax\.googleapis\.com[^>]+jquery[^>]*>\s*</script>',
                  '<script src="js/jquery-3.6.4.min.js"></script>', html, flags=re.I)
    if "jquery-3.6.4.min.js" not in html:
        # 没有匹配到就手工插在 </head> 前
        html = html.replace("</head>", '<script src="js/jquery-3.6.4.min.js"></script>\n</head>', 1)
    if "s.classList.remove('show')" not in html:
        html = html.replace("</body>", FALLBACK + "\n</body>", 1)
    index.write_text(html, encoding="utf-8")
    print("index.html 已更新，大小", len(before), "->", len(html))
    print("引用本地 jQuery:", "js/jquery-3.6.4.min.js" in html)
    print("兜底脚本:", "s.classList.remove('show')" in html)


if __name__ == "__main__":
    main()
