#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Round 278: add 5 independent UCLA PhD pages (Statistics / Economics / Biostatistics / Management / Medical Informatics)."""
import os, re, ast

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

PAGES = [
    {
        "id": "ucla-statistics-phd",
        "s": "ucla",
        "n": "统计学博士",
        "en": "Statistics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 10, 2026 (PhD); Jan 15, 2027 (MS); Fall admission only",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17); IELTS overall 7.0",
        "test": {"cls": "GRE General Highly Recommended per Department of Statistics and Data Science; no GRE Subject Test required; ETS institution code 4837; scores valid 5 years; PhD direct admission requires upper-division GPA at least 3.5; MS requires 3.2 upper-division GPA"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $120 US / $140 International; major code 0891; strong quantitative preparation required (at least 12 quarter upper-division courses in statistics, mathematics, computer science, or electrical engineering)",
        "url": "details/ucla-statistics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Statistics and Data Science",
        "website": "https://statistics.ucla.edu/academics/graduate/",
        "overview": "The UCLA Statistics PhD is a doctoral program offered by the Department of Statistics and Data Science. The PhD track trains students in theoretical and applied statistics, with strengths in high-dimensional data analysis, statistical machine learning, causal inference, Bayesian methodology, probability, and financial statistics. The department admits PhD applicants only in the Fall quarter. A bachelor's degree in statistics is not required, but applicants must have substantial upper-division quantitative preparation.",
        "requirements": "Bachelor's degree from an accredited institution. For direct admission to the doctoral program, a cumulative grade-point average of at least 3.5 in upper-division courses is required; applicants who already hold a master's degree must have maintained an average of better than 3.5 in graduate study. Required preparation: at least 12 quarter courses (or eight semester courses) in substantial upper-division quantitative work, including but not limited to statistics, mathematics, computer science, and electrical engineering. Three letters of recommendation that emphasize preparation for graduate study in statistics. Statement of Purpose and Personal Statement. The department's supplemental application is required in addition to the UCLA Graduate Division application.",
        "research": "Research areas: high-dimensional statistics, statistical machine learning, causal inference, Bayesian statistics and modeling, probability theory, stochastic processes, financial statistics and econometrics, statistical genetics, bioinformatics, data science, statistical computing, and applications in biology, engineering, finance, and the social sciences. Students complete coursework, preliminary and qualifying examinations, and dissertation research under faculty supervision. Typical time to degree within 5-6 years.",
    },
    {
        "id": "ucla-economics-phd",
        "s": "ucla",
        "n": "经济学博士",
        "en": "Economics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (11:59pm PST / 2:59am EST Dec 2); Fall admission only",
        "lang": "TOEFL iBT minimum 87 (no sub-section minimum required as long as overall 87 is met); IELTS overall band 7.0; TOEFL PBT 560 / CBT 220; ETS institution code 4837, dept 84; TOEFL scores valid 2 years",
        "test": {"cls": "GRE General REQUIRED for all applicants regardless of degree or major background; no GMAT substitute; no GRE Subject Test required; ETS institution code 4837, dept 1801 (Economics); self-reported score acceptable for review but official score required if admitted; scores must be dated within 5 years of application; admitted student GRE distribution ranges are not minimum thresholds"},
        "tui": "Full tuition + stipend + health insurance guaranteed for all admitted PhD students; application fee $120 US / $140 International; major code 0246; department admits PhD applicants only (no terminal MA); strongly recommends undergraduate training in economics, mathematics, and statistics",
        "url": "details/ucla-economics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Economics, College of Letters and Science",
        "website": "https://economics.ucla.edu/graduate/ph-d-program/",
        "overview": "The UCLA Economics PhD is a doctoral program in the Department of Economics. The department admits only applicants whose objective is the PhD - it does not admit students to a terminal MA. The program prepares students for academic careers in research universities and for research positions in government, central banks, international organizations, and the private sector. The program admits once a year, in the Fall quarter only.",
        "requirements": "Bachelor's degree from an accredited institution with a strong academic record. It is strongly recommended that applicants have undergraduate training in economics, mathematics, and statistics. Three letters of recommendation. Statement of Purpose. Unofficial transcripts uploaded by December 1. GRE/TOEFL exams must have been taken by December 1, with scores expected to arrive within 2-3 weeks. Letters of recommendation are given a two-week grace period. Decisions are typically released by late February / early March; acceptance reply deadline April 15.",
        "research": "Research areas: microeconomic theory, macroeconomics, econometrics, labor economics, public economics, industrial organization, international trade and finance, development economics, environmental economics, behavioral and experimental economics, economic theory, and applied microeconomics. The department hosts the California Center for Population Research and the UCLA Event Project. Students complete first-year core coursework in micro, macro, and econometrics, followed by field courses and dissertation research.",
    },
    {
        "id": "ucla-biostatistics-phd",
        "s": "ucla",
        "n": "生物统计学博士",
        "en": "Biostatistics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Priority); Fall admission only; applications via SOPHAS first, then UCLA Graduate Division",
        "lang": "TOEFL iBT / IELTS required for international applicants; UCLA minimum TOEFL iBT 87 (W25/S24/R21/L17); international applicants must submit transcripts through World Education Services (WES)",
        "test": {"cls": "GRE General OPTIONAL for all applicants to MS and PhD programs regardless of prior degrees or background; no GRE Subject Test required; ETS institution code 4225 (Fielding School of Public Health); three letters of recommendation; applicants with less than three years of post-bac professional experience should submit at least two academic letters and one professional letter"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee via SOPHAS + UCLA Graduate Division; major code 0132; PhD applicants strongly advised to complete real analysis (UCLA Math 131A/B) and linear algebra (UCLA Math 115A/B) prior to enrollment",
        "url": "details/ucla-biostatistics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Biostatistics, Jonathan and Karin Fielding School of Public Health",
        "website": "https://ph.ucla.edu/departments/biostatistics",
        "overview": "The UCLA Biostatistics PhD is a doctoral program in the Department of Biostatistics at the Fielding School of Public Health. The program develops the statistical foundations that shape how researchers understand disease, evaluate treatments, and improve human health. The department also offers MS in Biostatistics and Master of Data Science in Health (MDSH); PhD admission is through the SOPHAS centralized application service followed by the UCLA Graduate Division application.",
        "requirements": "Bachelor's degree from an accredited institution. Prior academic or professional experience in public health or a related field is not required as a condition of admission. Minimal mathematics for MS: two years of college-level mathematics including integral and differential calculus, multivariable calculus, differential equations, and linear algebra. For PhD: additional coursework in real analysis and junior/senior-level mathematics is highly recommended (UCLA Math 131A, 131B, 115A, 115B are desirable). Applicants whose undergraduate coursework is deficient may be admitted but will be required to take specified undergraduate courses upon matriculation. Three letters of recommendation. Official transcripts from each institution attended; international applicants must use WES for evaluation.",
        "research": "Research areas: Bayesian statistics, causal inference, statistical computing, data science, high-dimensional data analysis, statistical genetics, functional and longitudinal data analysis, hierarchical and multivariate models, imaging, phylogenetics, spatial statistics, survival analysis, and optimal design. Faculty collaborate across UCLA's medical school, School of Public Health, and the life sciences. Students complete coursework, qualifying examinations, and dissertation research. PhD students are typically supported by research assistantships on faculty grants.",
    },
    {
        "id": "ucla-management-phd",
        "s": "ucla",
        "n": "管理学博士（安德森商学院）",
        "en": "Management PhD (Anderson School of Management)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years typical",
        "ddl": "Jan 1, 2027 (first Friday in January for Fall 2027); Fall admission only",
        "lang": "TOEFL required for international applicants whose first language is not English; waiver only for applicants holding a bachelor's or higher degree from a university in the US, Australia, Barbados, Canada, Ireland, Jamaica, New Zealand, or the United Kingdom",
        "test": {"cls": "GRE or GMAT required (GRE preferred); no minimum score; ETS institution code 4837; three letters of recommendation preferably from academics who can judge research potential; admission rate approximately 5 percent of applicants annually"},
        "tui": "Full tuition + stipend + health insurance guaranteed for all admitted PhD students; application fee $135 US citizens/permanent residents, $155 international; major code 0535; admits PhD applicants only (MS degree awarded en route to PhD); note DOTM and Quantitative Marketing tracks are not accepting applications for 2027-28 cycle",
        "url": "details/ucla-management-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "John E. Anderson Graduate School of Management",
        "website": "https://www.anderson.ucla.edu/degrees/phd-program",
        "overview": "The UCLA Anderson Management PhD is a doctoral program offered through the John E. Anderson Graduate School of Management. The program admits only applicants whose objective is the PhD. The program offers academic areas including Accounting, Decisions Operations and Technology Management (DOTM), Finance, Global Economics and Management, Marketing, Management and Organizations, and Information Systems. Admission is highly selective (approximately 5 percent of applicants).",
        "requirements": "Bachelor's degree from an accredited institution with a minimum 3.0 GPA (or equivalent). Admitted students generally exhibit proficiency in business administration, quantitative methods, or one of the social sciences. GRE or GMAT required (GRE preferred). Three letters of recommendation, preferably from academics or others who can judge research potential. Statement of Purpose only (Personal History Statement optional). Scanned transcripts and degree certificates from each institution attended uploaded to the online application; official transcripts are not required during the application process. Admission decisions are made by April 15; the academic year begins mid-September.",
        "research": "Research areas by academic area: Accounting (financial accounting, management accounting, auditing, taxation); Finance (asset pricing, corporate finance, investments, financial institutions); Marketing (consumer behavior, quantitative marketing, marketing models); Management and Organizations (organizational behavior, sociology, psychology); Information Systems (economics of information systems, digital strategy); Global Economics and Management (international business, economic geography); Decisions Operations and Technology Management (operations management, operations research, information technology). Students complete coursework, field tutorials, and dissertation research leading to academic careers.",
    },
    {
        "id": "ucla-medical-informatics-phd",
        "s": "ucla",
        "n": "医学信息学博士",
        "en": "Medical Informatics PhD",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years typical",
        "ddl": "Dec 1, 2026 (Fall admission only)",
        "lang": "TOEFL required for international applicants; ETS institution code 4837, dept 30 (Other Biological Sciences); TOEFL scores take 6-8 weeks from test date for domestic scores and at least 8 weeks for international scores; applicants should take TOEFL by early November to ensure arrival by December 1",
        "test": {"cls": "GRE General NOT required per current admissions page; no GRE Subject Test required; ETS institution code 4837, dept 30 (Other Biological Sciences); three letters of recommendation from professors, supervisors, or others who can evaluate research accomplishments and potential; CV/résumé and 1-paged SOP and 1-paged Personal Statement required"},
        "tui": "Full tuition + stipend + health insurance guaranteed for admitted PhD students; application fee $135 US / $155 International; major code 0335; GPB Home Area; applicants select 'Biosciences PHD - Medical Informatics' as Major on Plans for Graduate Study page",
        "url": "details/ucla-medical-informatics-phd.html",
        "school": "University of California, Los Angeles",
        "dept": "Department of Health Policy and Management / Medical Informatics, GPB Home Area",
        "website": "https://medicalinformatics.ucla.edu/",
        "overview": "The UCLA Medical Informatics PhD is a GPB Home Area within the Graduate Programs in Bioscience at UCLA. The program trains students to develop and evaluate novel informatics approaches to clinically and translationally relevant problems in medicine and healthcare systems. It is closely aligned with the Bioinformatics interdepartmental PhD program. The Home Area also offers an MS in Bioinformatics (separate application).",
        "requirements": "Bachelor's degree from an accredited institution. The program seeks applicants with strong computational training (e.g., a bachelor's degree in computer science, bioengineering, or data science), as well as candidates from biomedical or clinical disciplines who demonstrate quantitative proficiency including programming, statistics, and data analysis. A background comparable to the requirements for UCLA's bachelor's degree in Computational and Systems Biology is desirable; a background in computer science and mathematics is desirable. Deficiencies should be addressed through preparatory study. One-page Statement of Purpose addressing: (1) what aspect of biomedical informatics interests you most; (2) describe research experience(s) including publications. One-page Personal Statement. CV. Writing sample not required (upload blank document when prompted). Unofficial transcripts at application; official transcripts required before admission (one of the few GPB Home Areas requiring transcripts before admission).",
        "research": "Research areas: clinical informatics, biomedical informatics, translational bioinformatics, imaging informatics, population health data science, machine learning in medicine, natural language processing of clinical text, electronic health records, wearable and sensor data, AI-driven clinical decision support, and health services research. The admissions committee uses the Statement of Purpose as the basis for matching academic and research interests to faculty. Selected applicants are invited for interview; admission offers follow. PhD only - MS in Bioinformatics is a separate program through the Bioinformatics Interdepartmental Program.",
    },
]

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()
