import re
from pathlib import Path

ROOT = Path(r"D:\work buddy\2026-11-05-14-15-52")
INDEX = ROOT / "index_main.html"

PAGES = {
    "ucsd-astro-phd": {
        "id": "ucsd-astro-phd",
        "s": "ucsd",
        "n": "天文与天体物理博士",
        "en": "PhD in Astronomy and Astrophysics (UC San Diego Department of Astronomy & Astrophysics)",
        "dept": "Department of Astronomy & Astrophysics",
        "college": "UC San Diego Division of Physical Sciences",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only)",
        "ddl": "Dec 4, 2026 (Fall 2027 application; application opens Sep 2, 2026).",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum). ETS institution code 4836. TOEFL not required for English-speaking international universities on IAU WHED database.",
        "test": {
            "cls": "GRE General and Physics Subject Test NOT required for Fall 2027 (department explicitly states GRE/PGRE are not required; scores may be submitted as optional elements but low scores ignored). No Subject GRE required."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. Application fee $135 (US) / $155 (international); fee waivers available (must submit by Nov 27).",
        "url": "details/ucsd-astro-phd.html",
        "school": "UC San Diego",
        "website": "https://astro.ucsd.edu/grad/",
        "overview": "The PhD in Astronomy and Astrophysics at UC San Diego provides focused training in observational, experimental, and theoretical astrophysics. Faculty research spans the full range of cosmic scales, from exoplanets to cosmology. Research areas include star and planet formation, galaxy formation and evolution, plasma astrophysics, general relativity, nuclear and particle astrophysics, cosmology, astrobiology, and astronomical instrumentation. UCSD has access to W.M. Keck Observatory, Lick Observatory, the Simons Observatory, and all US national facilities. Students complete 10 graduate courses and two quarters of independent research by the end of the second year.",
        "requirements": "Required: bachelor's degree in Astronomy, Physics, or related field. GPA minimum 3.0 (UCSD Graduate Division). 3-5 letters of recommendation. Statement of Purpose. CV/Resume. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Coursework and research experience in Astronomy desirable but not required. Contact: astro-grad@ucsd.edu.",
        "research": "Curriculum: 10 graduate courses including core astrophysics (stellar structure, galactic dynamics, cosmology, plasma astrophysics), advanced electives, and two quarters of second-year research. Research groups: Exoplanets, Galaxy Evolution, Cosmology, High-Energy Astrophysics, Astronomical Instrumentation. Facilities: Keck Observatory, Lick Observatory, Simons Observatory, Hubble Space Telescope, JWST, and all US national facilities."
    },
    "ucsd-bioinfo-phd": {
        "id": "ucsd-bioinfo-phd",
        "s": "ucsd",
        "n": "生物信息与系统生物学博士",
        "en": "PhD in Bioinformatics and Systems Biology (UC San Diego, two tracks: Bioinformatics & Systems Biology / Biomedical Informatics)",
        "dept": "Bioinformatics and Systems Biology Program",
        "college": "UC San Diego / School of Biological Sciences / School of Medicine / Jacobs School of Engineering",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only)",
        "ddl": "Nov 18, 2026 (Fall 2027 application; fee waiver requests due one week earlier). NOTE: this deadline is ~2 weeks earlier than most other UCSD PhD programs.",
        "lang": "TOEFL iBT / IELTS Academic / PTE Academic / Duolingo English Test (DET). ETS institution code 4836, department code 0224 (Bioinformatics); TOEFL department code 69 (Engineering).",
        "test": {
            "cls": "GRE General Test OPTIONAL for Fall 2027 (department FAQ states 'Due to the impact of COVID-19, GRE General Test scores are optional for applications for Fall 2027 admissions'). No Subject GRE required. Note: UCSD CSE PhD with Bioinformatics specialization is a separate program; this is the independent Bioinformatics & Systems Biology PhD.",
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and training grants. Application fee $135 (US) / $155 (international).",
        "url": "details/ucsd-bioinfo-phd.html",
        "school": "UC San Diego",
        "website": "https://bioinformatics.ucsd.edu/admissions/grad/admissions",
        "overview": "The PhD in Bioinformatics and Systems Biology at UC San Diego is an interdisciplinary program spanning four schools (Biological Sciences, Physical Sciences, Jacobs School of Engineering, and Health Sciences). Students indicate priority interest in either the Bioinformatics and Systems Biology Track or the Biomedical Informatics Track. The most competitive applicants have undergraduate degrees in biological sciences, physical sciences, computer science, or mathematics, with strong background in complementary disciplines. The program emphasizes quantitative and computational approaches to biology and medicine.",
        "requirements": "Required: bachelor's degree in biological sciences, physical sciences, computer science, or mathematics. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE optional. International students: TOEFL/IELTS/PTE/DET required. Strong quantitative background (linear algebra, statistics, programming) expected. Contact: bioinfo-admissions@ucsd.edu.",
        "research": "Curriculum: core bioinformatics, algorithms, statistics, genomics, proteomics, systems biology, biomedical informatics, and a doctoral dissertation. Research areas: computational biology, genomics, machine learning in biology, biomedical data science, health informatics, structural biology, and synthetic biology. Students rotate through faculty laboratories across four UCSD schools."
    },
    "ucsd-biostat-phd": {
        "id": "ucsd-biostat-phd",
        "s": "ucsd",
        "n": "生物统计学博士",
        "en": "PhD in Biostatistics (UC San Diego Herbert Wertheim School of Public Health and Human Longevity Science)",
        "dept": "Teaching Division of Biostatistics and Bioinformatics",
        "college": "UC San Diego Herbert Wertheim School of Public Health",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only)",
        "ddl": "Dec 2, 2026 (Fall 2027 doctoral application; MS deadline is Jan 6, 2027; if applying to both, must apply by PhD deadline).",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum). ETS institution code 4836.",
        "test": {
            "cls": "GRE General Test REQUIRED for PhD program (department explicitly requires GRE; MCAT is NOT accepted as substitute). No minimum GRE score; scores are interpreted holistically. Note: MS in Biostatistics has GRE optional, but PhD still requires GRE. This is one of the few UCSD public health PhD programs still mandating GRE.",
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and training grants. US citizens/permanent residents required to complete FAFSA for grant eligibility. Application fee $135 (US) / $155 (international).",
        "url": "details/ucsd-biostat-phd.html",
        "school": "UC San Diego",
        "website": "https://ph.ucsd.edu/phd/biostat/prospective-students-phd/index.html",
        "overview": "The PhD in Biostatistics at UC San Diego Herbert Wertheim School of Public Health provides rigorous training in statistical theory and methods for biomedical and public health research. The program requires 6 mathematics department courses, reflecting the strong mathematical foundation expected of students. Graduates pursue careers in academia, government research, pharmaceutical industry, and data science. The MS in Biostatistics is a separate professional degree with a later January deadline and GRE-optional policy.",
        "requirements": "Required: bachelor's degree with strong quantitative background (mathematics, statistics, or related field). GPA minimum 3.0. 3 letters of recommendation (at least 2 academic/professional for biostatistics PhD). Statement of Purpose. Official transcripts. List of mathematics courses taken/projected with textbooks and grades. GRE General REQUIRED. International students: TOEFL required. Contact: biostatistics@health.ucsd.edu.",
        "research": "Curriculum: 6 mathematics department courses (probability, mathematical statistics, linear models, statistical inference), core biostatistics (regression, categorical data, survival analysis, longitudinal data), advanced electives, and a doctoral dissertation. Research areas: clinical trials, genomic statistics, environmental statistics, health disparities, machine learning in biomedicine, and causal inference."
    },
    "ucsd-sio-phd": {
        "id": "ucsd-sio-phd",
        "s": "ucsd",
        "n": "斯克里普斯海洋研究所博士",
        "en": "PhD in Oceanography / Earth Sciences / Marine Biology (UC San Diego Scripps Institution of Oceanography)",
        "dept": "Scripps Institution of Oceanography (SIO)",
        "college": "UC San Diego Scripps Institution of Oceanography",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only; direct admit to advisor)",
        "ddl": "Dec 2, 2026 (Fall 2027 application; application opens Sep 16, 2026).",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum). ETS institution code 4836.",
        "test": {
            "cls": "GRE NOT required for Fall 2027 (Scripps explicitly states 'GRE test scores are not be required for admission; if you have already taken the test, you can include your scores on your application'). Scores may be considered in holistic review but are not required. No Subject GRE required.",
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. Direct admit to specific advisor; funding tied to advisor's research grants. Application fee $135 (US) / $155 (international).",
        "url": "details/ucsd-sio-phd.html",
        "school": "UC San Diego",
        "website": "https://scripps.ucsd.edu/doctoral",
        "overview": "The PhD program at Scripps Institution of Oceanography (SIO) offers three degree majors: Earth Sciences (SI76), Marine Biology (SI77), and Oceanography (SI78). Applicants select up to two of three research programs: Climate-Ocean-Atmosphere Program (COAP), Geosciences of the Earth, Oceans, and Planets (GEO), and Ocean Biosciences Program (OBP). SIO is one of the world's premier oceanographic and earth science research institutions, with research spanning physical oceanography, marine biology, marine chemistry, geosciences, climate science, and climate change. Admissions are driven by available funding and research projects; students are directly admitted to a specific advisor.",
        "requirements": "Required: bachelor's degree in physical, biological, or earth sciences; mathematics or engineering science also accepted. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE not required. International students: TOEFL required. Expected preparation: mathematics through differential and integral calculus, one year of physics with lab, one year of chemistry with lab, and an additional year of physics/chemistry/mathematics. Contact: sio-gradoffice@ucsd.edu.",
        "research": "Curriculum: core courses in oceanography/earth sciences/marine biology, advanced electives, comprehensive exam at end of first year, advancement to candidacy by end of third year, and dissertation completion by end of fifth year. Research groups: Physical Oceanography, Marine Biology, Marine Chemistry & Geochemistry, Climate-Ocean-Atmosphere (COAP), Geosciences of the Earth Oceans and Planets (GEO), Ocean Biosciences (OBP), Applied Ocean Science, and Marine Policy."
    },
    "ucsd-cogsci-phd": {
        "id": "ucsd-cogsci-phd",
        "s": "ucsd",
        "n": "认知科学博士",
        "en": "PhD in Cognitive Science (UC San Diego Department of Cognitive Science)",
        "dept": "Department of Cognitive Science",
        "college": "UC San Diego Division of Social Sciences",
        "disc": "sci",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-7 years full-time (Fall admission only; PhD-only, no MS program)",
        "ddl": "Dec 2, 2026 (Fall 2027 application; application opens Sep 2, 2026).",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum; TOEFL only required for international applicants whose native language is not English and who have not studied one uninterrupted year at an English-language university). ETS institution code 4836.",
        "test": {
            "cls": "GRE NOT required nor taken into consideration (department explicitly states 'GRE scores are not required nor taken into consideration'; no Subject Test required). Note: this is PhD-only program; no master's degree offered. Students who leave before PhD completion may request an en route MS if coursework and second-year project are completed.",
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. Application fee $135 (US) / $155 (international).",
        "url": "details/ucsd-cogsci-phd.html",
        "school": "UC San Diego",
        "website": "https://cogsci.ucsd.edu/graduates/phd-program/",
        "overview": "The PhD in Cognitive Science at UC San Diego is one of the world's top cognitive science programs, emphasizing four main areas: Brain (neurobiological processes and phenomena), Behavior (experimental methods in psychology, language, and sociocultural environment), Computation (representational formats and computational mechanisms), and Interaction (cognitive potential and consequences of technology and design). The program is PhD-only; no terminal master's degree is offered. UCSD Cognitive Science is the birthplace of the modern cognitive science field and has renowned faculty in embodied cognition, computational neuroscience, language acquisition, and human-computer interaction. Recent admissions: ~12 students admitted from ~151 applications (8% acceptance rate), average GPA 3.6.",
        "requirements": "Required: bachelor's degree in any field (program accepts students from all backgrounds; many have also completed a master's). GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE not required. International students: TOEFL/IELTS required. The program values diverse disciplinary backgrounds and interdisciplinary thinking. Contact: cogsphd@ucsd.edu, Cognitive Science Building CSB 145.",
        "research": "Curriculum: first year Foundations and Issues courses, second year basic courses and laboratory rotations with a year-long research project, candidacy exams by end of fourth year, and dissertation research. Research areas: embodied cognition, computational neuroscience, psycholinguistics, developmental cognitive science, human-computer interaction, machine learning and cognition, cognitive robotics, and cultural cognition. The department also offers an Interdisciplinary PhD Program in Cognitive Science (IDPCogSci) with home departments including Anthropology, Communication, CSE, Linguistics, Neurosciences, Philosophy, Psychology, and Sociology."
    },
}

# Render detail pages
TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school} {deg} {n} - 项目详情</title>
<style>
body{{font-family:-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;max-width:1100px;margin:24px auto;padding:0 20px;color:#222;line-height:1.7;background:#fafafa}}
h1{{color:#1a3a6c;border-bottom:3px solid #c8102e;padding-bottom:10px;font-size:1.6em}}
h2{{color:#1a3a6c;margin-top:28px;font-size:1.2em;border-left:4px solid #c8102e;padding-left:10px}}
.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin:18px 0}}
.card{{background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:14px;box-shadow:0 1px 3px rgba(0,0,0,0.06)}}
.card b{{color:#c8102e;display:block;margin-bottom:4px;font-size:0.9em}}
.card span{{font-size:0.95em}}
a{{color:#1a5fb4;word-break:break-all}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a3a6c;padding:2px 8px;border-radius:4px;font-size:0.85em;margin-right:6px}}
</style>
</head>
<body>
<h1>{school} {deg} · {n}</h1>
<p><span class="tag">{en}</span><span class="tag">{college}</span><span class="tag">{dept}</span></p>
<div class="grid">
<div class="card"><b>学位</b><span>{deg}（{lvl_label}）</span></div>
<div class="card"><b>时长</b><span>{dur}</span></div>
<div class="card"><b>截止日期</b><span>{ddl}</span></div>
<div class="card"><b>语言要求</b><span>{lang}</span></div>
<div class="card"><b>标化考试</b><span>{test_cls}</span></div>
<div class="card"><b>学费/资助</b><span>{tui}</span></div>
</div>
<h2>项目概览</h2>
<p>{overview}</p>
<h2>申请要求</h2>
<p>{requirements}</p>
<h2>课程与研究方向</h2>
<p>{research}</p>
<h2>官方链接</h2>
<p>官网项目页：<a href="{website}" target="_blank">{website}</a></p>
</body>
</html>"""

def render_page(p):
    lvl_label = "博士项目" if p["lvl"] == "d" else "硕士项目"
    test_cls = p["test"]["cls"]
    return TEMPLATE.format(
        school=p["school"], deg=p["deg"], n=p["n"], en=p["en"],
        college=p["college"], dept=p["dept"], lvl_label=lvl_label,
        dur=p["dur"], ddl=p["ddl"], lang=p["lang"], test_cls=test_cls,
        tui=p["tui"], overview=p["overview"], requirements=p["requirements"],
        research=p["research"], website=p["website"],
    )

for key, p in PAGES.items():
    out = ROOT / "details" / f"{key}.html"
    out.write_text(render_page(p), encoding="utf-8")
    print(f"Written: details/{key}.html")

html = INDEX.read_text(encoding="utf-8")
before_size = len(html.encode("utf-8"))
print(f"\nBefore size: {before_size} bytes")

def build_program_record(p):
    stem_val = 1 if p["stem"] else 0
    return (
        f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",'
        f'deg:"{p["deg"]}",lvl:"{p["lvl"]}",stem:{stem_val},dur:"{p["dur"]}",'
        f'ddl:"{p["ddl"]}",lang:"{p["lang"]}",test:{{cls:"{p["test"]["cls"]}"}},'
        f'tui:"{p["tui"]}",url:"{p["url"]}"}}'
    )

new_records = ",".join(build_program_record(p) for p in PAGES.values())

prog_match = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
if not prog_match:
    raise Exception("PROGRAMS array not found")

start = prog_match.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
    i += 1

insert_pos = i - 1
j = insert_pos - 1
while j >= 0 and html[j] in ' \t\n\r':
    j -= 1
if html[j] != ',':
    new_block = "," + new_records
else:
    new_block = new_records

html = html[:insert_pos] + new_block + html[insert_pos:]

vd_match = re.search(r'const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', html)
if not vd_match:
    raise Exception("VD Set not found")

vd_start = vd_match.end()
depth = 1
i = vd_start
while i < len(html) and depth > 0:
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
    i += 1

vd_insert_pos = i - 1
vd_new_items = ",".join(f'"{p["url"]}"' for p in PAGES.values())

j = vd_insert_pos - 1
while j >= 0 and html[j] in ' \t\n\r':
    j -= 1
if html[j] != ',':
    vd_new_block = "," + vd_new_items
else:
    vd_new_block = vd_new_items

html = html[:vd_insert_pos] + vd_new_block + html[vd_insert_pos:]

after_size = len(html.encode("utf-8"))
print(f"After size: {after_size} bytes")
print(f"Delta: +{after_size - before_size} bytes")

INDEX.write_text(html, encoding="utf-8")
print(f"\nPROGRAMS appended: {len(PAGES)} entries")
print(f"VD appended: {len(PAGES)} urls")
print("Done!")
