#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Round 279: add 5 independent UCLA PhD pages (ECE / MCIP / Biomathematics / ChemE / Geophysics)."""
import os, re, ast

ROOT = os.path.dirname(os.path.abspath(__file__))
INDEX = os.path.join(ROOT, "index_main.html")

PAGES = [
    {
        "id": "ucla-ece-phd",
        "s": "ucla",
        "n": "电气与计算机工程博士",
        "en": "Electrical and Computer Engineering PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 15, 2026 11:59pm PT (application); Jan 3, 2027 5pm PT (test scores, letters, transcripts); Fall admission only",
        "lang": "TOEFL iBT minimum 87 (pre-Jan 21, 2026) or 4.5 (new scale on/after Jan 21, 2026); IELTS accepted; UCLA does not accept MyBest TOEFL; ETS institution code 4837, dept 1203",
        "test": {"cls": "GRE General Optional for 2027-2028 admissions cycle; applications with GRE scores are not given greater weight than those without; GRE exemption reviewed for cohort beginning Fall 2028; no minimum GRE score; ETS institution code 4837, dept 1203; admitted student GRE distribution (V155/Q168/AW3.69) is non-binding reference, not a minimum threshold"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $120 US / $140 International; major code 0333; PhD applicants competitive with GPA at least 3.5; students already holding MS or PhD in ECE or closely related field (other engineering, CS, physics, math) are not admitted for a duplicate degree at the same level",
        "url": "details/ucla-ece-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Electrical and Computer Engineering, Samueli School of Engineering",
        "website": "https://www.ee.ucla.edu/graduate-application-requirements/",
        "overview": "The UCLA ECE PhD is a doctoral program in the Samueli School of Engineering. The program admits PhD applicants directly from the BS (no master's required); those admitted without an MS complete the UCLA MS in ECE en route to the PhD. The department offers research across six areas: circuits and embedded systems, communications and networking, control and dynamical systems, electronic and photonic devices, machine learning and computing, and signals and systems. Admission is once a year, Fall quarter only.",
        "requirements": "Bachelor's degree in electrical engineering or a closely related field. PhD applicants should have a GPA of at least 3.5 to be competitive. Three letters of recommendation. Statement of Purpose and Personal Statement. The ECE department section of the UCLA Graduate Division application is required. International students must meet the university TOEFL requirement; the ECE department cannot recommend admission for any international student who does not meet the university TOEFL requirement. Unofficial transcripts uploaded by the January 3 deadline; official transcripts required after admission.",
        "research": "Research areas: integrated circuits and embedded systems, communications and networking, control theory and dynamical systems, electronic and photonic devices and materials, machine learning and computing, signals and image processing, biomedical engineering, cyber-physical systems, and quantum engineering. Students complete first-year coursework, written and oral preliminary examinations, and dissertation research. The preliminary examination is held once each year and should be completed within two academic years of matriculation.",
    },
    {
        "id": "ucla-mcip-phd",
        "s": "ucla",
        "n": "分子细胞与整合生理学博士",
        "en": "Molecular, Cellular & Integrative Physiology PhD (MCIP)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only; GPB Home Area unified deadline)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17); ETS institution code 4837",
        "test": {"cls": "GRE General Not required / optional per UCLA GPB policy since September 2020; no GRE Subject Test required; ETS institution code 4837; three letters of recommendation; applicants may submit MCAT scores (MD applicants) if available"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $135 US / $155 International; major code 0568; interdepartmental program in the College of Letters and Science; official transcripts required after admission (one of the post-admission transcript Home Areas)",
        "url": "details/ucla-mcip-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Molecular, Cellular & Integrative Physiology Interdepartmental Program, GPB Home Area",
        "website": "https://grad.ucla.edu/programs/life-sciences/molecular-cellular-integrative-physiology/",
        "overview": "The UCLA Molecular, Cellular & Integrative Physiology (MCIP) PhD is an interdepartmental GPB Home Area. The program trains students to study physiological processes from the molecular and cellular level through to the integrated organ and organism level. It is the final GPB Home Area to be covered in the project library, completing the GPB Home Area set alongside BBS, CDB, GREAT, IMMP, Medical Informatics, Bioinformatics, Molecular Pharmacology, Human Genetics, and Neurosciences.",
        "requirements": "Bachelor's degree in a biological or physical science. Required university coursework: mathematics through calculus, college physics, general chemistry, organic chemistry, biochemistry, and biology. Cell and molecular biology courses are recommended. Applicants lacking preparation in a recommended course but with an otherwise outstanding record may be admitted provisionally with deficiencies corrected after enrollment. Three letters of recommendation. Essay describing academic background, work experience, motivation for research, and career goals. Unofficial transcripts at application; official transcripts required after admission. Applicants may apply directly or through UCLA Access to Programs in the Molecular and Cellular Life Sciences.",
        "research": "Research areas: cellular and molecular physiology, integrative physiology, systems physiology, neuroscience, cardiovascular physiology, respiratory physiology, epithelial physiology, muscle and contraction, endocrinology, reproductive physiology, developmental physiology, and computational physiology. Faculty are drawn from multiple departments across the College of Letters and Science, the David Geffen School of Medicine, and the UCLA College. Students complete laboratory rotations, coursework, qualifying examinations, and dissertation research.",
    },
    {
        "id": "ucla-biomathematics-phd",
        "s": "ucla",
        "n": "生物数学博士（计算医学）",
        "en": "Biomathematics PhD (Computational Medicine)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17); ETS institution code 4837",
        "test": {"cls": "GRE General and Subject OPTIONAL per current compmed.ucla.edu admissions page; scores from at least one standardized test (GRE General, GRE Science Subject, MCAT, or LSAT) are recommended but not required; ETS institution code 4837, dept 0225 (Computational Medicine); three letters of recommendation"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $120 US / $140 International; major code 0121; David Geffen School of Medicine; MS in Biomathematics is not currently accepting direct applications (MS is en route to PhD only)",
        "url": "details/ucla-biomathematics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Computational Medicine (Biomathematics), David Geffen School of Medicine",
        "website": "https://compmed.ucla.edu/phd/admissions",
        "overview": "The UCLA Biomathematics PhD is offered through the Department of Computational Medicine in the David Geffen School of Medicine. The program trains students at the intersection of mathematics, computer science, and biology/medicine. High academic achievement in one scientific or mathematical field is required; proficiency in both mathematics and biology is not necessary, but some prior preparation in both fields is desirable. The MS in Biomathematics is used primarily as a step to further graduate work and is not currently admitting direct MS students.",
        "requirements": "Bachelor's degree from an accredited institution with high academic achievement in one scientific or mathematical field. Statement of Purpose. Three letters of recommendation from faculty competent to evaluate qualifications for graduate study and a creative research career; additional letters are welcomed. Unofficial transcripts uploaded at application. Early offers for admissions with funding are made by mid-February or early March; the department follows the Council of Graduate Schools Resolution, with acceptance reply deadline April 15.",
        "research": "Research areas: computational medicine, biomedical informatics, machine learning in biology and medicine, medical imaging, genomic signal processing, systems biology, mathematical modeling of biological systems, bioinformatics, population health data science, and clinical decision support. Students are assigned a provisional adviser on arrival and are expected to identify a permanent dissertation adviser by the end of their second year. Doctoral committees replace provisional advisers once formed.",
    },
    {
        "id": "ucla-chem-eng-phd",
        "s": "ucla",
        "n": "化学与生物分子工程博士",
        "en": "Chemical and Biomolecular Engineering PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 31, 2026 (Fall admission only; no exceptions)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17)",
        "test": {"cls": "GRE General NOT required per current chemeng.ucla.edu PhD degree requirements page; GRE optional for MS/PhD per grad.ucla.edu major 0294; no GRE Subject Test required; ETS institution code 4837; three letters of recommendation"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $120 US / $140 International; major code 0294; minimum undergraduate GPA 3.5 for PhD (3.2 for MS); graduate course GPA requirement 3.33; Samueli School of Engineering",
        "url": "details/ucla-chem-eng-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Chemical and Biomolecular Engineering, Samueli School of Engineering",
        "website": "https://www.chemeng.ucla.edu/graduate-admissions/",
        "overview": "The UCLA Chemical and Biomolecular Engineering PhD is a doctoral program in the Samueli School of Engineering. The department offers MS and PhD degrees in Chemical Engineering, with specializations including semiconductor manufacturing, bioengineering, energy, polymers, materials, and process systems. The PhD program requires a minimum 3.5 undergraduate GPA; applicants not having adequate preparation may be admitted provisionally and required to take remedial coursework.",
        "requirements": "Bachelor's degree in engineering, chemistry, physics, or a related field with at least two years of preparation in mathematics, physics, chemistry, and engineering. Minimum undergraduate GPA 3.5 for PhD applicants (3.2 for MS). Three letters of recommendation. Statement of Purpose and Personal Statement (no formatting requirements). Department supplement not required. For applicants specializing in semiconductor manufacturing: BS in engineering or physical science is required; semiconductor industry experience is highly desirable but not required, and such experience should be documented in one of the letters of recommendation. Unofficial transcripts at application; official transcripts required only if requested by the admission committee.",
        "research": "Research areas: semiconductor manufacturing and processing, bioengineering and biomolecular engineering, energy and sustainability, polymers and soft matter, materials science, reaction engineering, process systems engineering, computational molecular engineering, and environmental engineering. PhD students must maintain a 3.33 graduate course GPA and enroll in Chemical Engineering 299 each quarter of residence. The recommended PhD timeline includes coursework, preliminary oral examination, and dissertation defense.",
    },
    {
        "id": "ucla-geophysics-space-physics-phd",
        "s": "ucla",
        "n": "地球物理与空间物理博士",
        "en": "Geophysics and Space Physics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission primary; Winter/Spring by consultation)",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17)",
        "test": {"cls": "GRE General Optional per grad.ucla.edu major 0406; Subject test scores optional but desirable, preferably in Physics, although Mathematics is also acceptable; ETS institution code 4837; three letters of recommendation"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $120 US / $140 International; major code 0406; Department of Earth, Planetary, and Space Sciences; qualified students may proceed directly toward the PhD, though most obtain the MS in the process",
        "url": "details/ucla-geophysics-space-physics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Earth, Planetary, and Space Sciences",
        "website": "https://grad.ucla.edu/programs/physical-sciences/earth-planetary-and-space-sciences/",
        "overview": "The UCLA Geophysics and Space Physics PhD is a doctoral program in the Department of Earth, Planetary, and Space Sciences. The program trains students in the physics of the Earth and planetary systems, including seismology, geomagnetism, space physics, plasma physics, planetary science, and geodynamic modeling. The department also offers MS and PhD degrees in Geochemistry, Geology, and Planetary Science.",
        "requirements": "Bachelor's degree in geology, physics, astronomy, engineering, mathematics, or a related field, with outstanding records in the relevant basic sciences and mathematics. Undergraduate work must include junior- or senior-level courses in mathematical methods, dynamics, electromagnetism, and thermodynamics. For applied geophysics specialization: undergraduate preparation equivalent to the Applied Geophysics curriculum, including Earth and Space Sciences 111, 112, 136A-C, 152, and Physics 105A/B, 110A/B, 114. Three letters of recommendation. Statement of Purpose. Qualified students may proceed directly toward the PhD, though most obtain the MS in the process.",
        "research": "Research areas: seismology and seismic imaging, geomagnetism and paleomagnetism, space physics and plasma physics, planetary science and geochemistry, geodynamics and computational geophysics, atmospheric science, remote sensing, and Earth system modeling. The UCLA Space Institute provides cross-departmental resources for experimental space physics, with research spanning atmospheric and oceanic sciences and physics and astronomy. Students complete written and oral qualifying examinations before advancing to doctoral candidacy.",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} - {en} | {school}</title>
<style>
body{{font-family:-apple-system,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;max-width:960px;margin:0 auto;padding:24px;color:#222;line-height:1.6}}
h1{{font-size:24px;border-bottom:3px solid #1a5fb4;padding-bottom:10px}}
h2{{font-size:18px;color:#1a5fb4;margin-top:28px;border-left:4px solid #1a5fb4;padding-left:10px}}
.meta{{background:#f5f7fa;padding:14px;border-radius:6px;margin:16px 0;display:grid;grid-template-columns:repeat(2,1fr);gap:8px 20px}}
.meta b{{color:#555}}
.card{{background:#fff;border:1px solid #e0e4ea;border-radius:8px;padding:16px;margin:12px 0;box-shadow:0 1px 3px rgba(0,0,0,.04)}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a5fb4;padding:2px 10px;border-radius:12px;font-size:12px;margin-right:6px}}
a{{color:#1a5fb4}}
</style>
</head>
<body>
<h1>{n} <small style="font-size:14px;color:#888">({en})</small></h1>
<p><span class="tag">{school}</span><span class="tag">{dept}</span><span class="tag">{lvl_label}</span></p>

<div class="meta">
<div><b>学位：</b>{deg}</div>
<div><b>学制：</b>{duration}</div>
<div><b>申请截止：</b>{ddl}</div>
<div><b>语言要求：</b>{lang}</div>
<div><b>标化：</b>{test_cls}</div>
<div><b>学费/资助：</b>{tui}</div>
</div>

<h2>项目概览</h2>
<div class="card"><p>{overview}</p></div>

<h2>申请要求</h2>
<div class="card"><p>{requirements}</p></div>

<h2>研究方向</h2>
<div class="card"><p>{research}</p></div>

<h2>官方链接</h2>
<div class="card"><p><a href="{website}" target="_blank">{website}</a></p></div>

<p style="color:#888;font-size:12px;margin-top:30px">本页面为项目库核验页，信息以学校官网最新公布为准。录取分布数据非最低门槛。</p>
</body>
</html>
"""


def append_programs_and_vd(html: str, new_entries: list) -> str:
    new_lines = []
    for p in new_entries:
        line = (
            f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",deg:"{p["deg"]}",'
            f'lvl:"{p["lvl"]}",stem:{p["stem"]},dur:"{p["dur"]}",ddl:"{p["ddl"]}",'
            f'lang:"{p["lang"]}",test:{{cls:"{p["test"]["cls"]}"}},tui:"{p["tui"]}",url:"{p["url"]}"}}'
        )
        new_lines.append(line)
    new_block = ",\n".join(new_lines)

    m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS array not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html) and depth > 0:
        ch = html[i]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
        i += 1
    close_pos = i - 1
    before = html[:close_pos].rstrip()
    after = html[close_pos:]
    if before.endswith(","):
        html = before + "\n" + new_block + "\n" + after
    else:
        html = before + ",\n" + new_block + "\n" + after

    m2 = re.search(r"const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\s*\[", html)
    if not m2:
        raise RuntimeError("VERIFIED_DETAILS set not found")
    vstart = m2.end()
    depth = 1
    j = vstart
    while j < len(html) and depth > 0:
        ch = html[j]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
        j += 1
    vclose = j - 1
    vd_urls = ",\n".join(f'"{p["url"]}"' for p in new_entries)
    vbefore = html[:vclose].rstrip()
    vafter = html[vclose:]
    if vbefore.endswith(","):
        html = vbefore + "\n" + vd_urls + "\n" + vafter
    else:
        html = vbefore + ",\n" + vd_urls + "\n" + vafter
    return html


def main():
    for p in PAGES:
        p["lvl_label"] = "Doctoral" if p["lvl"] == "d" else "Master's"
        p["duration"] = p["dur"]
        p["test_cls"] = p["test"]["cls"]

    for p in PAGES:
        out = DETAIL_TEMPLATE.format(**p)
        path = os.path.join(ROOT, p["url"].replace("/", os.sep))
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            f.write(out)
        print(f"wrote {p['url']}")

    with open(INDEX, "r", encoding="utf-8") as f:
        html = f.read()

    orig_size = len(html.encode("utf-8"))
    new_html = append_programs_and_vd(html, PAGES)
    new_size = len(new_html.encode("utf-8"))
    print(f"index_main.html: {orig_size} -> {new_size} bytes (delta +{new_size-orig_size})")

    with open(INDEX, "w", encoding="utf-8") as f:
        f.write(new_html)
    print("done.")


if __name__ == "__main__":
    main()
