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-cse-phd": {
        "id": "ucsd-cse-phd",
        "s": "ucsd",
        "n": "计算机科学与工程博士",
        "en": "PhD in Computer Science and Engineering (UC San Diego Department of Computer Science and Engineering)",
        "dept": "Department of Computer Science and Engineering (CSE)",
        "college": "UC San Diego Jacobs School of Engineering",
        "disc": "cs",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only)",
        "ddl": "Dec 16, 2026, 11:59pm PST (Fall 2027 application; application opens Sep 2, 2026).",
        "lang": "TOEFL iBT / IELTS Academic / Duolingo English Test (DET). ETS institution code 4836 (no department code needed). TOEFL not required for English-speaking international universities on IAU WHED database.",
        "test": {
            "cls": "GRE General Test NOT required for PhD and MS applications for Fall 2027 (department explicitly states 'The GRE is not required for PhD and MS applications for Fall 2027. Applicants may still submit valid scores if they have already taken the test.'). No Subject GRE required. No minimum GRE score; holistic review."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. Application fee $135 (US) / $155 (international); fee waivers available. MS students generally self-funded (partial TAships possible but not guaranteed).",
        "url": "details/ucsd-cse-phd.html",
        "school": "UC San Diego",
        "website": "https://cse.ucsd.edu/graduate/admissions",
        "overview": "The PhD in Computer Science and Engineering at UC San Diego is one of the top CS graduate programs in the world. The CSE department offers PhD research across all major areas of computer science: algorithms, artificial intelligence, computer architecture, computer vision, databases, graphics, HCI, programming languages, robotics, security, systems, and theory. The program is highly competitive, admitting roughly 10-15% of PhD applicants. UCSD CSE is particularly renowned for systems, networking, machine learning, and computer vision research. Students typically complete coursework and qualifying exams by the end of year 2, advance to candidacy by year 3, and defend by year 5-6.",
        "requirements": "Required: bachelor's degree in computer science, computer engineering, or a related field with strong mathematical background. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. CV/Resume. Official transcripts. GRE not required. International students: TOEFL/IELTS/DET required. Expected preparation: data structures, algorithms, operating systems, computer architecture, discrete math, probability, linear algebra. Contact: cse-admissions@ucsd.edu.",
        "research": "Curriculum: 12+ graduate courses in CS core (algorithms, systems, theory, AI/ML), breadth requirements, depth electives, thesis proposal by end of year 2, candidacy exam, and dissertation. Research areas: AI/ML, Computer Vision, NLP, Systems & Networking, Security, Theory, HCI, Graphics, Robotics, Programming Languages, Databases. Faculty include numerous ACM Fellows and AAAI Fellows; UCSD CSE consistently ranked top 10 in US News."
    },
    "ucsd-ece-phd": {
        "id": "ucsd-ece-phd",
        "s": "ucsd",
        "n": "电子与计算机工程博士",
        "en": "PhD in Electrical and Computer Engineering (UC San Diego Department of Electrical and Computer Engineering)",
        "dept": "Department of Electrical and Computer Engineering (ECE)",
        "college": "UC San Diego Jacobs School of Engineering",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-7 years full-time (Fall admission only; BS entrants 7 years support limit, MS entrants 6 years)",
        "ddl": "Dec 16, 2026 (PhD, Fall 2027); MS deadline is Jan 6, 2027. Application opens Sep 2, 2026.",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum). ETS institution code 4836; ECE department code 1203 (optional). TOEFL department code 66 (optional).",
        "test": {
            "cls": "GRE General Test NOT required for both MS and PhD applications for Fall 2027 (department FAQ explicitly states 'For Fall 2027 applications, submitting GRE scores is not required for either M.S. or Ph.D. applications'). Note: Fall 2026 cycle still required GRE for MS; this is a new policy change for Fall 2027. 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). MS students generally self-funded. Students entering with MS from another institution expected to complete PhD requirements one year earlier.",
        "url": "details/ucsd-ece-phd.html",
        "school": "UC San Diego",
        "website": "https://ece.ucsd.edu/graduate/graduate-admissions",
        "overview": "The PhD in Electrical and Computer Engineering at UC San Diego offers research training across 12 disciplines within ECE: applied ocean sciences, applied physics, communications theory and systems, computer engineering, electronic circuits and systems, intelligent systems, materials science, mechanical engineering (joint), photonics, signal and image processing, solid-state electronics, and systems control. UCSD ECE is particularly renowned for photonics, wireless communications, signal processing, and semiconductor devices. The comprehensive exam (PhD Preliminary) must be completed before the start of winter quarter of second year; the university qualifying exam must be completed before the start of fifth year.",
        "requirements": "Required: B.S. and/or M.S. degree in engineering, physical sciences, or mathematics from an accredited institution. Minimum cumulative GPA 3.0 (on 4.0 scale). 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE not required. International students: TOEFL/IELTS required. Contact: ece-grad@ucsd.edu.",
        "research": "Curriculum: graduate courses in ECE core and chosen area, comprehensive exam (Preliminary) by end of year 2, university qualifying exam by end of year 4, and dissertation defense by year 5-7. Research areas: Photonics & Optical Engineering, Wireless Communications, Signal & Image Processing, Semiconductor Devices, Embedded Systems & Computer Engineering, Machine Learning, Control Systems, Applied Ocean Sciences, Applied Physics, Circuits & VLSI, Intelligent Systems."
    },
    "ucsd-math-phd": {
        "id": "ucsd-math-phd",
        "s": "ucsd",
        "n": "数学博士",
        "en": "PhD in Mathematics (UC San Diego Department of Mathematics; three tracks: Pure Mathematics / Computational Science / Statistics)",
        "dept": "Department of Mathematics",
        "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 2, 2026 (PhD, Fall 2027; all three PhD tracks share same deadline). MA/MS deadline is Feb 3, 2027. Application opens Sep 2, 2026.",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum). ETS institution code 4836.",
        "test": {
            "cls": "GRE General Test and GRE Mathematics Subject Test are NOT required for Fall 2027 admissions. However, the GRE Mathematics Subject Test is HIGHLY RECOMMENDED, as it provides the Admissions Committee with additional context to assess applicants' preparedness. No minimum GRE score. Note: older UCSD catalog page still lists GRE as required; the department's current How to Apply and FAQ pages are authoritative (not required). Recommended: take Math Subject test no later than October for December 2 deadline."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via teaching assistantships, research assistantships, and fellowships. Departmental support is typically awarded only to PhD students (MA/MS students generally self-funded). Application fee $135 (US) / $155 (international).",
        "url": "details/ucsd-math-phd.html",
        "school": "UC San Diego",
        "website": "https://mathematics.ucsd.edu/students/graduate/how-to-apply",
        "overview": "The PhD in Mathematics at UC San Diego offers three doctoral tracks: (1) Pure Mathematics, (2) Mathematics with a Specialization in Computational Science, and (3) Mathematics with a Specialization in Statistics. The Pure Mathematics track covers analysis, algebra, topology, geometry, and applied mathematics. The Computational Science track integrates mathematics with scientific computing and data-driven modeling. The Statistics track prepares students for research in theoretical and applied statistics. UCSD Mathematics is renowned for analysis, geometry, and probability. The department also offers MA in Pure Mathematics and MA in Applied Mathematics as separate terminal master's degrees with a later February deadline.",
        "requirements": "Required: bachelor's or master's degree in mathematics or a related field. Minimum scholastic average of B (3.0/4.0) in upper-division or prior graduate coursework. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE not required (Math Subject highly recommended). International students: TOEFL/IELTS required. Contact: mathgradadmissions@ucsd.edu.",
        "research": "Curriculum: core graduate courses in analysis (real/complex), algebra, topology, numerical analysis, statistics, and electives. Three research areas: Area 1 (Complex Analysis, Real Analysis), Area 2 (Algebra, Applied Algebra, Topology), Area 3 (Numerical Analysis, Statistics, Applied Mathematics). Students take preliminary exams by end of year 2, advance to candidacy by year 3, and defend dissertation by year 5-6. The department also offers a joint PhD in Mathematics and Science Education (MSED) with SDSU."
    },
    "ucsd-se-phd": {
        "id": "ucsd-se-phd",
        "s": "ucsd",
        "n": "结构工程博士",
        "en": "PhD in Structural Engineering (UC San Diego Department of Structural Engineering)",
        "dept": "Department of Structural Engineering (SE)",
        "college": "UC San Diego Jacobs School of Engineering",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-7 years full-time (Fall admission only; students can apply directly to PhD without MS)",
        "ddl": "Dec 16, 2026 (PhD, Fall 2027). SE PhD Joint Doctoral Program with SDSU (SE 77) deadline is Dec 1, 2026. Application opens Sep 9, 2026.",
        "lang": "TOEFL iBT / IELTS Academic (required for all international students). ETS institution code 4836 (no department code needed).",
        "test": {
            "cls": "GRE test requirement is PERMANENTLY WAIVED (department FAQ explicitly states 'The GRE test requirement is permanently waived. With that said, because the Department of Structural Engineering reviews all application materials in its entirety, GRE scores will also be considered if submitted.'). No minimum GRE score. Note: older catalog page (2021-22 archive) still lists GRE as required; the current department FAQ is authoritative."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. Application fee $135 (US) / $155 (international). Students can apply directly to PhD program without holding an MS degree first.",
        "url": "details/ucsd-se-phd.html",
        "school": "UC San Diego",
        "website": "https://se.ucsd.edu/academics/graduate-program/admissions-faqs",
        "overview": "The PhD in Structural Engineering at UC San Diego prepares students for careers in research, teaching, and advanced professional practice. UCSD Structural Engineering is unique in its interdisciplinary approach, combining structural engineering with materials science, geotechnical engineering, computational mechanics, earthquake engineering, and coastal/Offshore engineering. The department is renowned for earthquake engineering research, large-scale structural testing, and computational mechanics. Students take SE 290 seminar every quarter during the first year. The PhD qualifying examination covers structural mechanics, materials, and a focus area chosen by the student.",
        "requirements": "Required: BS in engineering, physical sciences, or mathematics with overall upper-division GPA of 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE permanently waived (submitted scores considered holistically). International students: TOEFL/IELTS required. Students can apply directly to PhD without MS. Contact: se-grad@ucsd.edu.",
        "research": "Curriculum: graduate courses in structural engineering core (structural analysis, design, dynamics, materials), focus area electives, departmental PhD qualifying exam (DQE), university qualifying exam, and dissertation. Research focus areas: Earthquake Engineering, Structural Dynamics, Computational Mechanics, Materials Engineering, Geotechnical Engineering, Coastal/Offshore Engineering, Smart Structures & Sensors, Resilient Infrastructure. Precandidacy limited to 4 years; university support for 6 years; dissertation defense within 7 years."
    },
    "ucsd-mae-phd": {
        "id": "ucsd-mae-phd",
        "s": "ucsd",
        "n": "机械与航天工程博士",
        "en": "PhD in Mechanical and Aerospace Engineering (UC San Diego Department of Mechanical and Aerospace Engineering)",
        "dept": "Department of Mechanical and Aerospace Engineering (MAE)",
        "college": "UC San Diego Jacobs School of Engineering",
        "disc": "eng",
        "lvl": "d",
        "deg": "PhD",
        "stem": 1,
        "dur": "5-6 years full-time (Fall admission only; typical timeline: DQE by end of year 2, Senate Exam by year 4, defense by year 5)",
        "ddl": "Dec 2, 2026 (PhD, Fall 2027). MS deadline is Jan 13, 2027. Application opens Sep 2, 2026.",
        "lang": "TOEFL iBT / IELTS Academic (UCSD minimum). ETS institution code 4836.",
        "test": {
            "cls": "GRE NOT REQUIRED (GRE Optional; department states 'Our graduate programs are GRE Optional, meaning that faculty admissions evaluators can see whether an applicant has submitted GRE scores and what the scores are when they are submitted.'). Offered applicants typically provide quantitative GRE score in 85-90 percentile and above (this is a distribution, not a minimum threshold). Self-reported GRE scores accepted at application; official scores required after matriculation."
        },
        "tui": "Fully funded for PhD admits (stipend + tuition + fees) via GSR/GSI appointments and fellowships. Application fee $135 (US) / $155 (international). MS students generally self-funded. Engineering Physics PhD track has extended time limits (7 years support, 8 years registered) due to interdisciplinary coursework.",
        "url": "details/ucsd-mae-phd.html",
        "school": "UC San Diego",
        "website": "https://mae.ucsd.edu/grad/graduate-admissions",
        "overview": "The PhD in Mechanical and Aerospace Engineering at UC San Diego offers research training across six specializations: Aerospace Engineering, Applied Mechanics, Applied Ocean Sciences, Engineering Physics, Mechanical Engineering, and Computational Science (added 2007). The program requires three examinations: Departmental Qualifying Exam (DQE, oral committee exam within first six quarters), Senate Exam (University Qualifying Exam, advancement to candidacy before completion of 4th year), and Dissertation Defense. UCSD MAE is particularly renowned for aerospace engineering, fluid mechanics, combustion, materials, and controls. The department has strong ties to the local San Diego aerospace and defense industry (SpaceX, General Atomics, Northrop Grumman).",
        "requirements": "Required: bachelor's degree in mechanical engineering, aerospace engineering, or related engineering/science field. GPA minimum 3.0. 3 letters of recommendation. Statement of Purpose. Official transcripts. GRE optional. International students: TOEFL/IELTS required. Expected preparation: advanced calculus, differential equations, linear algebra, classical mechanics, thermodynamics, fluid mechanics, heat transfer, materials, and dynamics. Contact: mae-grad@ucsd.edu.",
        "research": "Curriculum: 36 units of graduate coursework in MAE core, DQE oral exam by end of year 2 (6 quarters), Senate Exam by year 4, and dissertation defense by year 5-6. Research areas: Aerospace Engineering (aerodynamics, propulsion, structural dynamics), Applied Mechanics (solid mechanics, materials, fatigue), Applied Ocean Sciences (ocean acoustics, underwater vehicles, marine hydrodynamics), Engineering Physics (combustion, energy, plasma physics), Mechanical Engineering (controls, robotics, MEMS, manufacturing), Computational Science (numerical methods, HPC, data-driven engineering). Precandidacy limited to 4 years; university support 6 years (7 for Engineering Physics); defense within 7 years (8 for Engineering Physics)."
    },
}

# 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!")
