# -*- coding: utf-8 -*-
"""Round 224: batch add 5 Operations Research / Management Science PhD programs
- col-ieor-phd (Columbia IEOR PhD)
- stanford-msande-phd (Stanford MS&E PhD)
- mit-orc-phd (MIT Operations Research Center PhD)
- berkeley-ieor-phd (UC Berkeley IEOR PhD)
- cmu-tepper-om-phd (CMU Tepper PhD Operations Management)
Key finding: MIT ORC is GRE-optional; other 4 still require GRE/GMAT. Deadlines: Dec 1 (Stanford MS&E, MIT ORC) vs Dec 15 (Columbia, Berkeley, CMU).
"""
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
DET = os.path.join(BASE, "details")
os.makedirs(DET, exist_ok=True)

PROGRAMS = [
    {
        "id": "col-ieor-phd",
        "s": "col",
        "n": "工业工程与运筹学博士",
        "en": "PhD in Industrial Engineering & Operations Research (Columbia University, SEAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time; 4 core courses in Year 1 (Optimization I/II, Stochastic Models I/II); qualifying exam (GPA 3.66+); research begins summer Year 1; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Decision late February / early March. Fall entry only; no spring admission.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Columbia SEAS graduate admissions.",
        "test": {"cls": "GRE historically required (per department FAQ: 'we recommend preparing the GRE exam as it has historically been a hard requirement'). GMAT also accepted. No minimum score. Prerequisites: Real Analysis, Linear Algebra, Probability and Statistics. Programming experience preferred."},
        "tui": "All admitted PhD students receive full funding: tuition + health insurance + monthly stipend for at least 4 years, typically extended to 5th year with satisfactory progress. Teaching assistantships and SEAS fellowships available.",
        "url": "details/col-ieor-phd.html",
    },
    {
        "id": "stanford-msande-phd",
        "s": "stanford",
        "n": "管理科学与工程博士",
        "en": "PhD in Management Science & Engineering (Stanford University School of Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time; minimum 135 units; at least 2 years in residence at Stanford; breadth requirement + depth in one research area; fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm PST). Decision mid-February (rolling by research area). Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Stanford graduate admissions.",
        "test": {"cls": "GRE required (department FAQ states 'we do not waive the GRE based upon work experience'). ETS code 4704. Prerequisites: MATH 51 (linear algebra, multivariable calculus) and CS 106A (programming) or equivalent. Additional coursework in statistics and economics preferred."},
        "tui": "Full financial fellowship: tuition + stipend + health insurance. Knight-Hennessy Scholars available. Research assistantships and teaching assistantships available.",
        "url": "details/stanford-msande-phd.html",
    },
    {
        "id": "mit-orc-phd",
        "s": "mit",
        "n": "运筹学博士",
        "en": "PhD in Operations Research (MIT Operations Research Center)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time; PhD and SM in OR offered through the ORC; fall-only admission; STEM-designated",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM Eastern Time). Application opens September 1. Fall entry only. Fee $90.",
        "lang": "TOEFL iBT minimum 100; IELTS minimum 7.0. ETS code 3514. TOEFL scores must be within past 2 years.",
        "test": {"cls": "GRE OPTIONAL (per ORC FAQ: 'Applications submitted with a GRE score should not have any advantage over applications submitted without a GRE score'). ETS code 3514 if submitted. This is a key differentiator: MIT ORC is GRE-free unlike most business/engineering PhD programs."},
        "tui": "All admitted PhD students receive full funding: tuition + stipend + health insurance. NSF GRFP eligible. Research assistantships and teaching assistantships available.",
        "url": "details/mit-orc-phd.html",
    },
    {
        "id": "berkeley-ieor-phd",
        "s": "berkeley",
        "n": "工业工程与运筹学博士",
        "en": "PhD in Industrial Engineering & Operations Research (UC Berkeley College of Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time; research-oriented academic PhD; ranked #3 nationally by USNews; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (8:59pm PST). Decision mid-March. Deadline to accept offer: April 15, 2027. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Berkeley graduate division.",
        "test": {"cls": "GRE required for all applicants EXCEPT UC degree holders with 3.5+ cumulative or advanced GPA (current UC students, transfer students). ETS code 4833 (Graduate Organizations, no department code). No minimum score. UC alumni/current students may also be eligible for application fee waivers."},
        "tui": "All admitted PhD students receive full funding: tuition + stipend + health insurance. Research assistantships and teaching assistantships available. Fellowships available (e.g., Marie Pelagie Elimbi Moudio Fellowship).",
        "url": "details/berkeley-ieor-phd.html",
    },
    {
        "id": "cmu-tepper-om-phd",
        "s": "cmu",
        "n": "运营管理博士",
        "en": "PhD in Operations Management (Tepper School of Business, Carnegie Mellon University)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years full-time; 144 units in first 2 years; 3 tracks (I. Modeling and Methodology / II. Modeling and Theoretical Analysis / III. Modeling and Empirical Analysis); minor area concentration (18 units); fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Decisions posted no earlier than January 15, all by April 15. Fall entry only.",
        "lang": "TOEFL iBT, IELTS, or Duolingo English Test (DET) accepted. ETS code 2074 (Tepper PhD, NOT 4883 which is for masters). No waivers.",
        "test": {"cls": "GRE or GMAT required (both accepted; no waivers). ETS code 2074; GMAT program code 69H-XH-19. Scores valid 5 years. Note: Economics PhD at Tepper prefers GRE; OM accepts both."},
        "tui": "All admitted PhD students receive full funding: tuition + stipend + health insurance. Tepper has a long tradition in operations management (top-ranked MBA OM program) and interdisciplinary ties with CMU engineering, public policy, HCI, and psychology.",
        "url": "details/cmu-tepper-om-phd.html",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{school} - {en}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6}}
h1{{font-size:24px;border-bottom:2px solid #1a73e8;padding-bottom:8px}}
h2{{font-size:18px;color:#1a73e8;margin-top:24px}}
.card{{background:#f8f9fa;border-left:4px solid #1a73e8;padding:12px 16px;margin:12px 0;border-radius:4px}}
.meta{{display:grid;grid-template-columns:120px 1fr;gap:6px 12px;font-size:14px}}
.meta b{{color:#555}}
ul{{margin:6px 0;padding-left:20px}}
.note{{background:#fff3cd;border-left-color:#ffc107;padding:10px 14px;margin-top:16px;font-size:13px}}
a{{color:#1a73e8}}
</style>
</head>
<body>
<h1>{school} - {en}</h1>
<div class="card">
<div class="meta">
<b>Degree</b><span>{deg}</span>
<b>Level</b><span>Research Doctorate (PhD)</span>
<b>STEM</b><span>{stem_label}</span>
<b>Duration</b><span>{dur}</span>
<b>Deadline</b><span>{ddl}</span>
<b>Language</b><span>{lang}</span>
<b>Standardized</b><span>{test_cls}</span>
<b>Funding</b><span>{tui}</span>
</div>
</div>

<h2>Program Overview</h2>
<div class="card">
{overview}
</div>

<h2>Admissions Requirements</h2>
<div class="card">
{requirements}
</div>

<h2>Research Areas</h2>
<div class="card">
{research}
</div>

<h2>Official Source</h2>
<div class="card">
{source}
</div>

<div class="note">
<strong>Note:</strong> This is a research-oriented PhD program in operations research / management science. Admitted PhD students receive full financial support. Admission statistics shown are distribution ranges, not minimum thresholds. Course/credit details pending department bulletin verification.
</div>
</body>
</html>
"""

PAGES = {
    "col-ieor-phd": {
        "school": "Columbia University SEAS",
        "en": "PhD in Industrial Engineering & Operations Research",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes (STEM-designated engineering)",
        "dur": "4-5 years full-time; 4 core courses Year 1; qualifying exam; dissertation",
        "ddl": "Fall 2027: December 15, 2026. Decision late February / early March. Fall only.",
        "lang": "TOEFL or IELTS required per Columbia SEAS graduate admissions.",
        "test_cls": "GRE historically required; GMAT also accepted. No minimum score. Prerequisites: Real Analysis, Linear Algebra, Probability & Statistics.",
        "tui": "Full funding: tuition + health insurance + monthly stipend for at least 4 years (usually 5).",
        "overview": "Columbia IEOR is a multi-disciplinary applied science department using mathematical models to improve decision-making in complex environments. Faculty are recognized for foundational contributions to optimization, statistics, machine learning, and probability. Research areas include healthcare operations, financial engineering, supply chain management, and market design.",
        "requirements": "<ul><li>Bachelor's degree; proficiency in Real Analysis, Linear Algebra, Probability and Statistics</li><li>GRE or GMAT (historically required)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, transcripts</li><li>Letters of recommendation</li><li>December 15, 2026 deadline</li><li>Fall entry only; no spring admission</li><li>Programming experience preferred</li></ul>",
        "research": "<ul><li>Optimization (continuous, discrete, stochastic)</li><li>Stochastic modeling and simulation</li><li>Machine learning and statistics</li><li>Financial engineering and quantitative finance</li><li>Supply chain and operations management</li><li>Healthcare operations and health policy</li><li>Market design and auctions</li><li>Revenue management and pricing</li></ul>",
        "source": '<a href="https://ieor.columbia.edu/phd-program" target="_blank">Columbia IEOR PhD Program</a> | <a href="https://ieor.columbia.edu/graduate-programs-timelines" target="_blank">Graduate Timelines</a> | <a href="https://ieor.columbia.edu/ieor-admissions" target="_blank">Admissions</a>',
    },
    "stanford-msande-phd": {
        "school": "Stanford University",
        "en": "PhD in Management Science & Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes (STEM-designated engineering)",
        "dur": "4-5 years full-time; 135 units; at least 2 years in residence; breadth + depth requirement",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm PST). Decision mid-February. Fall only.",
        "lang": "TOEFL or IELTS required per Stanford graduate admissions.",
        "test_cls": "GRE required (no waiver based on work experience). ETS 4704. Prerequisites: MATH 51 (linear algebra, multivariable calculus) and CS 106A (programming).",
        "tui": "Full fellowship: tuition + stipend + health insurance. Knight-Hennessy Scholars available.",
        "overview": "Stanford MS&E PhD is intended for students interested in research and teaching careers or high-level technical work in universities, industry, or government. The program requires a minimum of 135 units and is organized around breadth across all department areas plus depth in one.",
        "requirements": "<ul><li>Bachelor's degree</li><li>GRE required (no waiver)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, transcripts, CV</li><li>Letters of recommendation</li><li>December 1, 2026 11:59pm PST deadline</li><li>Prerequisites: MATH 51 (linear algebra, multivariable calculus), CS 106A (programming)</li><li>Fall entry only</li></ul>",
        "research": "<ul><li>Computational social science</li><li>Decision and risk analysis</li><li>Energy and environment</li><li>Health systems modeling and policy</li><li>Operations research</li><li>Organizations, technology, and entrepreneurship</li><li>Policy and strategy</li><li>Quantitative finance</li></ul>",
        "source": '<a href="https://msande.stanford.edu/academics-admissions/graduate/admission/phd-admission" target="_blank">Stanford MS&E PhD Admission</a> | <a href="https://bulletin.stanford.edu/programs/MGTSC-PHD" target="_blank">Stanford Bulletin: MGTSC-PHD</a> | <a href="https://msande.stanford.edu/academics-admissions/graduate/admission/admission-faqs" target="_blank">Admission FAQs</a>',
    },
    "mit-orc-phd": {
        "school": "MIT Operations Research Center",
        "en": "PhD in Operations Research",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes (STEM-designated)",
        "dur": "4-5 years full-time; PhD and SM in OR offered; fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM Eastern Time). Fee $90. Fall only.",
        "lang": "TOEFL iBT minimum 100; IELTS minimum 7.0. ETS code 3514. TOEFL scores within past 2 years.",
        "test_cls": "GRE OPTIONAL (per ORC FAQ: GRE scores provide no advantage). ETS code 3514 if submitted. Key differentiator: MIT ORC is GRE-free.",
        "tui": "Full funding: tuition + stipend + health insurance. NSF GRFP eligible. RA/TA available.",
        "overview": "The MIT Operations Research Center (ORC) is the recognized leader in operations research and analytics worldwide. It seeks applicants who aspire to make significant contributions in healthcare, finance, education, and transportation. The ORC offers PhD and SM in Operations Research, plus a Master of Business Analytics (MBAn).",
        "requirements": "<ul><li>Bachelor's degree</li><li>GRE optional (no advantage either way)</li><li>TOEFL 100 / IELTS 7.0 (international)</li><li>Statement of objectives (recommended ~1 page)</li><li>3 letters of recommendation</li><li>Transcripts</li><li>$90 application fee</li><li>December 1, 2026 11:59pm ET deadline</li><li>Fall entry only</li></ul>",
        "research": "<ul><li>Optimization (continuous, discrete, integer, stochastic)</li><li>Stochastic systems and simulation</li><li>Machine learning and statistics</li><li>Financial engineering and risk management</li><li>Healthcare operations and policy</li><li>Supply chain and logistics</li><li>Transportation and energy systems</li><li>Market design and revenue management</li></ul>",
        "source": '<a href="https://orc.mit.edu/admissions/" target="_blank">MIT ORC Admissions</a> | <a href="https://orc.mit.edu/admissions/faq/" target="_blank">ORC FAQ</a> | <a href="https://oge.mit.edu/programs/operations-research-center/" target="_blank">MIT OGE: Operations Research Center</a>',
    },
    "berkeley-ieor-phd": {
        "school": "UC Berkeley IEOR",
        "en": "PhD in Industrial Engineering & Operations Research",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes (STEM-designated engineering)",
        "dur": "4-5 years full-time; research-oriented academic PhD; ranked #3 nationally by USNews",
        "ddl": "Fall 2027: December 15, 2026 (8:59pm PST). Decision mid-March. Accept offer by April 15, 2027. Fall only.",
        "lang": "TOEFL or IELTS required per Berkeley graduate division.",
        "test_cls": "GRE required except UC degree holders with 3.5+ GPA (current UC students, transfer students). ETS code 4833 (no department code). No minimum score. UC alumni/current students may also be eligible for fee waivers.",
        "tui": "Full funding: tuition + stipend + health insurance. RA/TA available. Departmental fellowships available.",
        "overview": "UC Berkeley IEOR is ranked #3 nationally. The PhD program prepares students with the latest theory, computational tools, and research methods for a career in academia or industry. Graduates go on to faculty positions at top universities and quantitative roles in finance, tech, healthcare, and consulting.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative background</li><li>GRE required (waived for UC degree holders with 3.5+ GPA)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, transcripts, resume</li><li>Letters of recommendation</li><li>December 15, 2026 8:59pm PST deadline</li><li>Fall entry only</li></ul>",
        "research": "<ul><li>Optimization and mathematical programming</li><li>Stochastic processes and simulation</li><li>Machine learning and data science</li><li>Financial engineering and quantitative finance</li><li>Supply chain and operations management</li><li>Healthcare operations and health policy</li><li>Energy and sustainability</li><li>Robotics and logistics</li><li>Revenue management and pricing</li></ul>",
        "source": '<a href="https://ieor.berkeley.edu/academics/phd/how-to-apply/" target="_blank">Berkeley IEOR PhD How to Apply</a> | <a href="https://ieor.berkeley.edu/academics/phd/" target="_blank">PhD Program Overview</a> | <a href="https://ieor.berkeley.edu/academics/phd/faq/" target="_blank">PhD FAQ</a>',
    },
    "cmu-tepper-om-phd": {
        "school": "Carnegie Mellon University Tepper",
        "en": "PhD in Operations Management",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes (STEM-designated)",
        "dur": "4-5 years full-time; 144 units in first 2 years; 3 tracks; minor area concentration (18 units)",
        "ddl": "Fall 2027: December 15, 2026. Decisions no earlier than January 15, all by April 15. Fall only.",
        "lang": "TOEFL iBT, IELTS, or Duolingo English Test (DET) accepted. ETS code 2074 (Tepper PhD, NOT 4883). No waivers.",
        "test_cls": "GRE or GMAT required (both accepted; no waivers). ETS code 2074; GMAT 69H-XH-19. Scores valid 5 years. Note: Tepper Economics prefers GRE; OM accepts both.",
        "tui": "Full funding: tuition + stipend + health insurance. Tepper has a long tradition in operations management and interdisciplinary ties with CMU engineering, public policy, HCI, and psychology.",
        "overview": "The Tepper PhD in Operations Management trains researchers and future faculty to develop scientific solutions to operations problems. The program is small and interdisciplinary, combining quantitative modeling with empirical studies using OR, stochastic processes, AI, statistics, econometrics, and economics.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative background</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL / IELTS / DET accepted</li><li>Statement of purpose, transcripts, CV</li><li>Letters of recommendation</li><li>December 15, 2026 deadline</li><li>Fall entry only</li><li>3 tracks: Modeling & Methodology / Modeling & Theoretical Analysis / Modeling & Empirical Analysis</li><li>Minor area concentration (18 units) in Probability/Statistics, Math, CS, OM, Finance, or Economics</li></ul>",
        "research": "<ul><li>Operations strategy and firm behavior</li><li>Supply chain management and contracting</li><li>Revenue management and pricing</li><li>Healthcare operations</li><li>Empirical operations management</li><li>Analytical modeling of service systems</li><li>Data-driven operations and AI</li><li>Market design and platform economics</li></ul>",
        "source": '<a href="https://www.cmu.edu/tepper/programs/phd/program/operations-management/index.html" target="_blank">CMU Tepper PhD Operations Management</a> | <a href="https://www.cmu.edu/tepper/programs/phd/admissions/" target="_blank">PhD Admissions</a> | <a href="https://www.cmu.edu/tepper/programs/phd/program/operations-management/requirements.html" target="_blank">Program Requirements</a>',
    },
}

# Write detail pages
for p in PROGRAMS:
    key = p["id"]
    d = PAGES[key]
    html = DETAIL_TEMPLATE.format(
        school=d["school"], en=d["en"], deg=d["deg"], stem_label=d["stem_label"],
        dur=d["dur"], ddl=d["ddl"], lang=d["lang"], test_cls=d["test_cls"], tui=d["tui"],
        overview=d["overview"], requirements=d["requirements"],
        research=d["research"], source=d["source"],
    )
    path = os.path.join(DET, key + ".html")
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Wrote: {key}.html")

# Append PROGRAMS
idx_path = os.path.join(BASE, "index_main.html")
with open(idx_path, "r", encoding="utf-8") as f:
    html = f.read()

def build_entry(p):
    return ('{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
            'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test_cls}"}},'
            'tui:"{tui}",url:"{url}"}}').format(
        id=p["id"], s=p["s"], n=p["n"], en=p["en"], deg=p["deg"], lvl=p["lvl"],
        stem=p["stem"], dur=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"].replace('"', "'"),
        tui=p["tui"].replace('"', "'"), url=p["url"],
    )

new_entries = ",\n".join(build_entry(p) for p in PROGRAMS)

m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
start = m.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[': depth += 1
    elif c == ']': depth -= 1
    i += 1
insert_pos = i - 1
prefix = html[:insert_pos].rstrip()
suffix = html[insert_pos:]
if prefix.endswith('{'):
    new_block = prefix + "\n" + new_entries + "\n" + suffix
else:
    new_block = prefix + ",\n" + new_entries + "\n" + suffix

# Append VD on new_block (re-locate to avoid offset)
vd_entries = ",\n".join(f'"{p["url"]}"' for p in PROGRAMS)
m2 = re.search(r'VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', new_block)
vstart = m2.end()
vdepth = 1
j = vstart
while j < len(new_block) and vdepth > 0:
    c = new_block[j]
    if c == '[': vdepth += 1
    elif c == ']': vdepth -= 1
    j += 1
vinsert_pos = j - 1
vprefix = new_block[:vinsert_pos].rstrip()
vsuffix = new_block[vinsert_pos:]
if vprefix.endswith(','):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
elif vprefix.endswith('['):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
else:
    new_block = vprefix + ",\n" + vd_entries + "\n" + vsuffix

with open(idx_path, "w", encoding="utf-8") as f:
    f.write(new_block)

print(f"Appended {len(PROGRAMS)} PROGRAMS entries and {len(PROGRAMS)} VD entries")
print(f"Done. File size: {os.path.getsize(idx_path)}")
