# -*- coding: utf-8 -*-
import io, sys, os, json, ssl, urllib.request, socket, re, html
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
todo={x["det"]:x for x in json.load(open("todo_upgrade.json",encoding="utf-8"))}
picks={"eds":"details/usc-c97fb24.html","mds":"details/usc-ce4fd5a.html","em":"details/usc-c32a6e0.html","pde":"details/usc-cc9187d.html","bio":"details/usc-c568b0a.html"}
socket.setdefaulttimeout(15)
for k,det in picks.items():
    x=todo[det]; u=x["url"]
    try:
        req=urllib.request.Request(u,headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/126.0"})
        b=urllib.request.urlopen(req,context=ctx).read()
        t=b.decode("utf-8","ignore")
        open(f"_usc4_{k}.html","wb").write(b)
        # 去标签转纯文本
        tt=re.sub(r'<script.*?</script>','',t,flags=re.S|re.I)
        tt=re.sub(r'<style.*?</style>','',tt,flags=re.S|re.I)
        tt=re.sub(r'<[^>]+>',' ',tt)
        tt=html.unescape(tt)
        tt=re.sub(r'\s+',' ',tt)
        open(f"_usc4_{k}.txt","w",encoding="utf-8").write(tt)
        print(k,"OK",len(b),"B  txt",len(tt),"|",x["en"])
    except Exception as e:
        print(k,"ERR",type(e).__name__,str(e)[:50])
