# -*- coding: utf-8 -*-
import sys, io, re, pathlib, requests
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"); CACHE = BASE / "cache"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"}
# fetch bcfm
u = "https://catalog.gatech.edu/programs/building-construction-facility-management-ms/"
r = requests.get(u, headers=UA, timeout=25)
print(u, r.status_code, len(r.text))
(CACHE / "gt-bcfm.html").write_text(r.text, encoding="utf-8", errors="ignore")

def clean(t):
    t = re.sub(r"<script.*?</script>", " ", t, flags=re.S)
    t = re.sub(r"<style.*?</style>", " ", t, flags=re.S)
    t = t.replace("&nbsp;", " ").replace("&amp;", "&").replace("&#39;", "'").replace("&quot;", '"')
    t = re.sub(r"<[^>]+>", "\n", t)
    lines = [re.sub(r"\s+", " ", x).strip() for x in t.split("\n")]
    return [x for x in lines if x]

def digest(name):
    lines = clean(CACHE.joinpath(name + ".html").read_text(encoding="utf-8", errors="ignore"))
    # 主内容起点：Program Information
    try:
        i = max(lines.index("Program Information"), lines.index("Program Requirements"))
    except ValueError:
        i = 0
    body = lines[i:]
    # 去重复导航尾巴
    return body

for name in ["gt-robotics","gt-bme","gt-bioe","gt-biology","gt-medphys","gt-mgmt","gt-bcfm","gt-econ","gt-math"]:
    d = digest(name)
    out = BASE / ("_r343_txt_" + name.replace("gt-","") + ".txt")
    out.write_text("\n".join(d), encoding="utf-8")
    print(name, "lines", len(d), "->", out.name, len(out.read_text(encoding='utf-8')))
