# -*- coding: utf-8 -*-
"""r344 落库：按 PROGRAMS 现有 url 渲染页面 + 回填 ddl/lang/test/tui（禁手写 HTML）"""
import sys, io, re, json, pathlib, shutil
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
BASE = pathlib.Path(r"D:\work buddy\2026-11-05-14-15-52")
sys.path.insert(0, str(BASE))
import detail_render

LANGS = "TOEFL：Overall ≥4.5（S3.5/W4/L4/R4，Essentials 口径）；IELTS Academic 7.0（W5.5/S6.5/L6.5/R6.5）"
STD_TUI = "标准 Graduate（Master & PhD）：居民 $607/学分（12+ $7,280）；非居民 $1,341/学分（12+ $16,073）；境外 $1,379/学分（12+ $16,540）"
DDL = "catalog 项目页未列申请截止（官网未披露）"
TEST = "官网未披露 GRE 要求"
FIELDS = {
 "gatech-ece-ms": (DDL, LANGS, TEST, "MSECE：居民 $711/学分（12+ $8,528）；非居民 $1,570/学分（12+ $18,830）；境外 $1,616/学分（12+ $19,377）"),
 "gatech-qcf-ms": (DDL, LANGS, TEST, "MSQCF：居民 $759/学分（12+ $9,103）；非居民 $1,778/学分（12+ $21,316）；境外 $1,829/学分（12+ $21,935）"),
 "gatech-sce-ms": (DDL, LANGS, TEST, "MSSCE：居民 $715/学分（12+ $8,575）；非居民 $1,742/学分（12+ $20,902）；境外 $1,793/学分（12+ $21,508）"),
 "gatech-ie-ms": (DDL, LANGS, TEST, STD_TUI),
 "gatech-or-ms": (DDL, LANGS, TEST, STD_TUI),
 "gatech-cse-ms": (DDL, LANGS, TEST, STD_TUI),
 "gatech-mse-ms": (DDL, LANGS, TEST, STD_TUI),
 "gatech-urban-analytics-ms": (DDL, LANGS, TEST, STD_TUI),
}
SPEC = BASE / "_r344_specs"
specs = {s["id"]: s for s in [json.load(open(SPEC / f"{i}.json", encoding="utf-8")) for i in json.load(open(SPEC / "_queue.json", encoding="utf-8"))]}

MAIN = BASE / "index_main.html"
shutil.copy2(MAIN, BASE / "index_main.html.bak_r344")
html = MAIN.read_text(encoding="utf-8")
seg_start = html.index("const PROGRAMS=[")
seg_end = html.index("const CATD=[")
seg = html[seg_start:seg_end]
blocks = [b for b in re.split(r'(?=\bid:")', seg) if 'id:"' in b]

done, missing = [], []
for i, b in enumerate(blocks):
    m = re.search(r'\bid:"([^"]+)"', b)
    pid = m.group(1) if m else ""
    if pid not in specs:
        continue
    spec = specs[pid]
    url = re.search(r'\burl:"([^"]+)"', b).group(1)
    out = BASE / url
    out.write_text(detail_render.render(spec), encoding="utf-8")
    ddl, lang, test, tui = FIELDS[pid]
    nb = re.sub(r'\bddl:"[^"]*"', lambda _m: 'ddl:"%s"' % ddl, b, count=1)
    nb = re.sub(r'\blang:"[^"]*"', lambda _m: 'lang:"%s"' % lang, nb, count=1)
    nb = re.sub(r'test\s*:\s*\{\s*cls\s*:\s*"[^"]*"\s*\}', lambda _m: 'test:{cls:"%s"}' % test, nb, count=1)
    nb = re.sub(r'\btui:"[^"]*"', lambda _m: 'tui:"%s"' % tui, nb, count=1)
    blocks[i] = nb
    done.append((pid, url, out.stat().st_size))
for pid in specs:
    if pid not in [d[0] for d in done]:
        missing.append(pid)

prefix = seg[:seg.index('id:"')]
new_seg = prefix + "".join(blocks)
html = html[:seg_start] + new_seg + html[seg_end:]
MAIN.write_text(html, encoding="utf-8")
print("written:", len(done), "missing:", missing)
for d in done:
    print("  ", d)
