# -*- coding: utf-8 -*-
"""Round 221: batch add 5 Public Policy / Management PhD programs
- harvard-ppol-phd (Harvard Kennedy School PhD in Public Policy)
- princeton-spia-phd (Princeton SPIA PhD in Public Affairs)
- uchicago-harris-phd (UChicago Harris PhD in Public Policy Studies)
- usc-price-phd (USC Price PhD in Public Policy and Management)
- col-susdev-phd (Columbia SIPA PhD in Sustainable Development)
Note: Duke Sanford PhD Public Policy NOT accepting 2027-28 applications (reopens 2028-29) -> excluded.
Note: Georgetown McCourt has no standalone PhD (only MPP/Government joint dual degree) -> excluded.
Pattern: 4/5 require GRE; Princeton SPIA PhD is GRE-free. Deadlines cluster Dec 1 (Harvard/Princeton/USC), Dec 3 (UChicago Harris), Dec 17 (Columbia).
"""
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": "harvard-ppol-phd",
        "s": "harvard",
        "n": "公共政策博士",
        "en": "PhD in Public Policy (PPOL, Harvard Kennedy School / Harvard Griffin GSAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years; admitted to one of four tracks (Economics / Judgment and Decision Making / Politics and Institutions / Science, Technology and Policy Studies); no terminal AM; fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM ET). Decisions announced in late February. Fall admission only.",
        "lang": "TOEFL iBT minimum 103 OR IELTS minimum 7. ETS code 3451 (Harvard Griffin GSAS), no department code. Waiver only for undergraduate degree from English-instruction institution; master's in English does not waive.",
        "test": {"cls": "GRE General REQUIRED; no waiver option; no GMAT/LSAT accepted. No minimum score. Scores must be within 5 years (tests taken no earlier than January 2021). Writing sample required: single-authored, English, no more than 20 pages. Three letters of recommendation."},
        "tui": "Fully funded by Harvard Griffin GSAS (tuition + stipend + health fees). PhD students may also pursue Harvard AM (in passing) after two years of coursework and oral general examination; no terminal AM admitted.",
        "url": "details/harvard-ppol-phd.html",
    },
    {
        "id": "princeton-spia-phd",
        "s": "princeton",
        "n": "公共事务博士",
        "en": "PhD in Public Affairs (Princeton School of Public and International Affairs, SPIA)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years; two research clusters: Security Studies OR Science, Technology and Environmental Policy (STEP); target enrollment ~8 students/year (4 per cluster); fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM ET). Single application deadline for MPA/MPP/PhD. Decisions by March 15; enrollment decision by April 15. Application fee $75.",
        "lang": "TOEFL/IELTS/DET required if undergraduate instruction not entirely in English or no one year of full-time graduate study in English. Princeton Graduate School has no minimum score.",
        "test": {"cls": "GRE NOT required for PhD applicants (MPA still requires GRE; MPP optional). PhD review centers on academic coursework, scholarly research, fit with faculty. Writing sample required: 20-25 page research paper. Three letters of recommendation. Quantitative baseline in economics/statistics/college math expected."},
        "tui": "Fully funded by Princeton Graduate School: tuition + stipend + health coverage. Note: only the STEP cluster is OPT-eligible; Security Studies cluster is not.",
        "url": "details/princeton-spia-phd.html",
    },
    {
        "id": "uchicago-harris-phd",
        "s": "uchicago",
        "n": "公共政策研究博士",
        "en": "PhD in Public Policy Studies (University of Chicago Harris School of Public Policy)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; at least 27 policy-relevant courses (18 graded A-C-, up to 9 R/P); four qualifying exams (methods, microeconomics, political economy, substantive field); dissertation; fall-only admission",
        "ddl": "Fall 2027: December 3, 2026. Three letters of recommendation. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers. Per University of Chicago Graduate International Admissions policy.",
        "test": {"cls": "GRE REQUIRED for PhD applicants; no waiver allowed. Institution code 1832. Self-reported scores accepted for review; official scores required upon admission. GMAT not accepted for PhD. Strong quantitative/analytical foundation expected (STAT24400, PPHA42000 Applied Econometrics)."},
        "tui": "Up to four years of full financial support: tuition + stipend. Harris PhD is DHS STEM-designated (24-month OPT extension eligible for F-1 students).",
        "url": "details/uchicago-harris-phd.html",
    },
    {
        "id": "usc-price-phd",
        "s": "usc",
        "n": "公共政策与管理博士",
        "en": "PhD in Public Policy and Management (DPPM, USC Price School of Public Policy)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years; 100% of PhD students receive 4 years of funding through fellowships and graduate assistantships; fall-only admission",
        "ddl": "Fall 2027: Scholarship & Final deadline December 1, 2026. One application cycle per year for fall admission. Application fee $90.",
        "lang": "TOEFL or IELTS required for non-native English speakers. USC international graduate admissions policy.",
        "test": {"cls": "GRE REQUIRED. Institution code 4852. Scores older than 5 years not accepted. Materials: official transcripts, 1000-word statement of purpose, ~10-page writing sample, current resume, 3 letters of recommendation (at least 2 academic). USC has zero-tolerance policy: generative AI use in application leads to immediate rejection."},
        "tui": "All PhD students receive 4 years of year-round full tuition + competitive stipend + health/dental insurance. Years beyond 4 supported via TA/RA or outside fellowships. Conference travel stipend available.",
        "url": "details/usc-price-phd.html",
    },
    {
        "id": "col-susdev-phd",
        "s": "col",
        "n": "可持续发展博士",
        "en": "PhD in Sustainable Development (Columbia School of International and Public Affairs, SIPA, through GSAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; full-time PhD; requires interdisciplinary coursework in natural sciences, social sciences, economics, and math; fall-only admission; no transfer from SIPA MIA/MPA",
        "ddl": "Fall 2027: December 17, 2026. Three letters of recommendation (at least 2 academic). Resume required; no writing sample required.",
        "lang": "TOEFL iBT preferred 110, minimum 100; IELTS preferred 7.5, minimum 7.0; Cambridge C1 Advanced minimum 185, preferred 191. Columbia does not accept at-home versions or MyBest scores.",
        "test": {"cls": "GRE General REQUIRED. GRE Subject not required. Prerequisites: 2 semesters of calculus (through multivariable) + linear algebra + 2 semesters of economics + 6 semesters of college-level math and science. No minimum GRE score."},
        "tui": "Fully funded by Columbia GSAS: tuition + stipend + health insurance. Note: SIPA MPA/MIA master's programs have GRE optional; only the PhD in Sustainable Development still requires GRE. No transfer credit from SIPA master's.",
        "url": "details/col-susdev-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. 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 = {
    "harvard-ppol-phd": {
        "school": "Harvard Kennedy School",
        "en": "PhD in Public Policy (PPOL)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "No (traditional social science policy doctorate)",
        "dur": "5-6 years; admitted to one of four tracks; no terminal AM; fall-only",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM ET). Decisions in late February.",
        "lang": "TOEFL iBT 103 or IELTS 7. ETS code 3451. Waiver only for undergraduate degree from English-instruction institution.",
        "test_cls": "GRE REQUIRED, no waiver; no GMAT/LSAT. Writing sample <=20 pages single-authored English. 3 letters.",
        "tui": "Fully funded by Harvard Griffin GSAS: tuition + stipend + health fees.",
        "overview": "The PhD in Public Policy (PPOL) is jointly administered by Harvard Kennedy School and Harvard Griffin GSAS. It balances theory with practical methods, training scholars for careers in academia, government, research organizations, and the private sector. Students matriculate into one of four tracks and cannot change tracks before matriculation.",
        "requirements": "<ul><li>Bachelor's degree; master's not required</li><li>Four tracks: Economics / Judgment and Decision Making / Politics and Institutions / Science, Technology and Policy Studies</li><li>GRE required (no waiver; GMAT/LSAT not accepted)</li><li>Writing sample <=20 pages, single-authored, English</li><li>3 letters of recommendation</li><li>Statement of purpose + personal statement</li><li>TOEFL 103 / IELTS 7</li><li>Fall admission only</li></ul>",
        "research": "<ul><li>Economics track: microeconomics, econometrics, public finance</li><li>Judgment and Decision Making: behavioral decision research</li><li>Politics and Institutions: political institutions, policy design</li><li>Science, Technology and Policy: STI policy, climate, energy</li><li>International development</li><li>Water resources, criminal justice disparities, welfare state politics</li></ul>",
        "source": '<a href="https://www.hks.harvard.edu/admissions-aid/doctoral-program-admissions/admissions-requirements" target="_blank">HKS Doctoral Admissions Requirements</a> | <a href="https://gsas.harvard.edu/program/public-policy" target="_blank">Harvard GSAS: Public Policy</a> | <a href="https://www.hks.harvard.edu/educational-programs/doctoral-programs/phd-public-policy/doctoral-student-handbook" target="_blank">Doctoral Student Handbook</a>',
    },
    "princeton-spia-phd": {
        "school": "Princeton SPIA",
        "en": "PhD in Public Affairs",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "STEP cluster is OPT-eligible; Security Studies is not",
        "dur": "5 years; two clusters: Security Studies OR STEP; ~8 students/year (4 per cluster)",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM ET). Decisions March 15; enrollment by April 15. Fee $75.",
        "lang": "TOEFL/IELTS/DET required if undergraduate not entirely in English. Princeton Graduate School has no minimum score.",
        "test_cls": "GRE NOT required for PhD (MPA still requires GRE). Writing sample 20-25 page research paper. 3 letters. Quantitative baseline in econ/stats/college math expected.",
        "tui": "Fully funded: tuition + stipend + health coverage. STEP cluster is OPT-eligible.",
        "overview": "Princeton School of Public and International Affairs (SPIA) offers a PhD in Public Affairs with two research clusters: Security Studies and Science, Technology and Environmental Policy (STEP). The program enrolls approximately 8 students per year, 4 in each cluster. Both clusters require advanced politics and econometrics training.",
        "requirements": "<ul><li>Bachelor's degree; master's recommended but not required</li><li>Choose cluster: Security Studies or STEP</li><li>GRE not required for PhD (changed from MPA requirement)</li><li>Writing sample: 20-25 page research paper</li><li>3 letters of recommendation</li><li>Statement of academic purpose, CV/resume</li><li>TOEFL/IELTS/DET (if applicable)</li><li>$75 application fee; fall admission only</li></ul>",
        "research": "<ul><li>Security Studies: international security, conflict, cyber</li><li>STEP: science, technology and environmental policy</li><li>Both clusters: advanced politics + econometrics</li><li>STEP requires >=8 courses in first 2 years, >=3 from SPIA or science/engineering</li><li>Original publishable-quality research paper required</li></ul>",
        "source": '<a href="https://spia.princeton.edu/graduate-admissions/faqs" target="_blank">SPIA Graduate Admissions FAQs</a> | <a href="https://spia.princeton.edu/graduate-admissions/phd-public-affairs/application" target="_blank">PhD Application</a> | <a href="https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/princeton-school-public-and-international-affairs" target="_blank">Princeton Graduate School: SPIA</a>',
    },
    "uchicago-harris-phd": {
        "school": "UChicago Harris School of Public Policy",
        "en": "PhD in Public Policy Studies",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes - DHS STEM-designated (24-month OPT extension eligible)",
        "dur": "4-5 years; at least 27 policy-relevant courses; four qualifying exams; dissertation",
        "ddl": "Fall 2027: December 3, 2026. 3 letters of recommendation. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per UChicago Graduate International Admissions policy.",
        "test_cls": "GRE REQUIRED; no waiver allowed for PhD. Institution code 1832. Self-reported accepted; official required on admission. GMAT not accepted for PhD.",
        "tui": "Up to 4 years full support: tuition + stipend. STEM-designated for OPT extension.",
        "overview": "The Harris School PhD in Public Policy Studies prepares students for research-oriented careers in academia, industry, and government. It emphasizes rigorous training in microeconomics, econometrics, and political economy, plus in-depth study of substantive policy areas. The degree is DHS STEM-designated.",
        "requirements": "<ul><li>Bachelor's degree</li><li>GRE required; no PhD waiver</li><li>3 letters of recommendation</li><li>Statement of purpose, CV, transcripts</li><li>TOEFL or IELTS (non-native English)</li><li>December 3, 2026 deadline</li><li>Strong quantitative foundation (STAT24400, PPHA42000 Applied Econometrics)</li><li>Four qualifying exams: methods, microeconomics, political economy, substantive field</li></ul>",
        "research": "<ul><li>Microeconomics and econometrics</li><li>Political economy</li><li>Poverty, inequality, economic growth</li><li>Education policy</li><li>Health economics</li><li>Environmental and energy policy</li><li>Joint PhD in Political Economy with Department of Political Science</li></ul>",
        "source": '<a href="https://harris.uchicago.edu/admissions/requirements-and-deadlines" target="_blank">Harris Requirements & Deadlines</a> | <a href="https://harris.uchicago.edu/academics/degrees/phd" target="_blank">Harris PhD Program</a> | <a href="https://harris.uchicago.edu/files/2018-19_phd_manual.pdf" target="_blank">PhD Policies & Procedures Manual (PDF)</a>',
    },
    "usc-price-phd": {
        "school": "USC Price School of Public Policy",
        "en": "PhD in Public Policy and Management (DPPM)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "No (traditional policy doctorate)",
        "dur": "4-5 years; 100% of PhD students receive 4 years funding via fellowships/GAships",
        "ddl": "Fall 2027: Scholarship & Final deadline December 1, 2026. One cycle per year. Fee $90.",
        "lang": "TOEFL or IELTS required for non-native English speakers per USC international graduate admissions.",
        "test_cls": "GRE REQUIRED. Institution code 4852. Scores >5 years not accepted. Materials: transcripts, 1000-word SOP, ~10-page writing sample, resume, 3 letters (>=2 academic). Generative AI use leads to immediate rejection.",
        "tui": "4 years year-round full tuition + competitive stipend + health/dental. Years 5+ via TA/RA or outside fellowships. Conference travel stipend.",
        "overview": "USC Price's PhD in Public Policy and Management (DPPM) combines theoretical and methodological training with specialization in policy areas such as economics, sociology, political science, and organizational theory. The program is ranked among the top public affairs schools by U.S. News. All PhD students are funded for four years.",
        "requirements": "<ul><li>Bachelor's degree from accredited institution</li><li>GRE required (code 4852; <=5 years old)</li><li>3 letters of recommendation (>=2 academic)</li><li>1000-word statement of purpose</li><li>~10-page writing sample</li><li>Current resume/CV</li><li>Official transcripts</li><li>$90 application fee</li><li>Fall admission only; December 1, 2026 deadline</li><li>Zero-tolerance: no generative AI in application</li></ul>",
        "research": "<ul><li>Economics, sociology, political science</li><li>Organizational theory</li><li>Urban policy and governance</li><li>Health policy</li><li>Nonprofit management</li><li>Land use and transportation policy</li><li>Los Angeles and Washington DC research presence</li></ul>",
        "source": '<a href="https://priceschool.usc.edu/academics/doctoral/ph-d-in-public-policy-and-management-ppm/" target="_blank">USC Price DPPM</a> | <a href="https://priceschool.usc.edu/academics/doctoral/phd-admissions/" target="_blank">PhD Admissions Materials</a> | <a href="https://catalogue.usc.edu/content.php?catoid=22&expand=1&navoid=9159" target="_blank">USC Catalogue: Price School</a>',
    },
    "col-susdev-phd": {
        "school": "Columbia SIPA",
        "en": "PhD in Sustainable Development",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Yes (interdisciplinary natural science + social science)",
        "dur": "5-6 years; full-time; interdisciplinary coursework in natural sciences, social sciences, economics, math; no transfer from SIPA MIA/MPA",
        "ddl": "Fall 2027: December 17, 2026. 3 letters of recommendation (>=2 academic). Resume required; no writing sample.",
        "lang": "TOEFL iBT preferred 110 / min 100; IELTS preferred 7.5 / min 7.0; Cambridge C1 Advanced min 185 / preferred 191. No at-home versions or MyBest scores.",
        "test_cls": "GRE General REQUIRED. GRE Subject not required. Prerequisites: 2 semesters calculus (through multivariable) + linear algebra + 2 semesters economics + 6 semesters college math/science.",
        "tui": "Fully funded by Columbia GSAS: tuition + stipend + health insurance. No transfer credit from SIPA master's.",
        "overview": "The PhD in Sustainable Development is offered by Columbia SIPA through the Graduate School of Arts and Sciences (GSAS). It requires interdisciplinary training in natural sciences, social sciences, and economics. Note: SIPA MPA/MIA master's programs are GRE-optional, but the PhD still requires GRE.",
        "requirements": "<ul><li>Bachelor's degree</li><li>GRE required (no at-home version)</li><li>3 letters of recommendation (>=2 academic)</li><li>Statement of academic purpose + personal statement</li><li>Resume required; no writing sample</li><li>TOEFL 100 (preferred 110) / IELTS 7.0 (preferred 7.5)</li><li>Prerequisites: 2 sem calculus through multivariable + linear algebra + 2 sem economics + 6 sem college math/science</li><li>December 17, 2026 deadline</li><li>Fall admission only; no transfer from SIPA MIA/MPA</li></ul>",
        "research": "<ul><li>Environmental and resource economics</li><li>Sustainable development economics</li><li>Climate change and energy</li><li>Poverty and inequality</li><li>Ecological economics</li><li>Global environmental governance</li><li>Natural science + social science integration</li></ul>",
        "source": '<a href="https://www.gsas.columbia.edu/content/sustainable-development" target="_blank">Columbia GSAS: Sustainable Development</a> | <a href="https://new.sipa.columbia.edu/sipa-education/doctoral-program/faqs" target="_blank">SIPA Sustainable Development FAQs</a> | <a href="https://www.sipa.columbia.edu/admissions/apply" target="_blank">SIPA Apply</a>',
    },
}

# Write detail pages
for p in PROGRAMS:
    key = p["id"]
    d = PAGES[key]
    stem_label = d["stem_label"]
    html = DETAIL_TEMPLATE.format(
        school=d["school"], en=d["en"], deg=d["deg"], dur=d["dur"],
        ddl=d["ddl"], lang=d["lang"], test_cls=d["test_cls"], tui=d["tui"],
        stem_label=stem_label,
        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)}")
