# -*- coding: utf-8 -*-
"""Round 220: batch add 5 Economics PhD programs
- harvard-econ-phd (Harvard Economics PhD)
- yale-econ-phd (Yale Economics PhD)
- princeton-econ-phd (Princeton Economics PhD)
- mit-econ-phd (MIT Economics PhD)
- nu-econ-phd (Northwestern Economics PhD)
Pattern: all top economics PhDs still REQUIRE GRE; deadlines cluster Dec 1 or Dec 15.
Reuses r218/r219 VD fix pattern.
"""
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-econ-phd",
        "s": "harvard",
        "n": "经济学博士",
        "en": "PhD in Economics (Harvard Kenneth C. Griffin GSAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; core micro/macro/econometrics plus field courses; writing sample required",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM ET). Fall admission only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per GSAS policy. Harvard TOEFL code 344.",
        "test": {"cls": "GRE General REQUIRED. No minimum score. Minimum math preparation: calculus, linear algebra, and demonstrated proficiency with mathematics. Writing sample required (single or co-authored accepted)."},
        "tui": "Fully funded by Harvard Griffin GSAS: tuition, stipend, and health fees. Department arranges campus visit weekend for all admitted students and covers a portion of visit costs. Note: Harvard Business Economics PhD (joint with HBS) is a separate program.",
        "url": "details/harvard-econ-phd.html",
    },
    {
        "id": "yale-econ-phd",
        "s": "yale",
        "n": "经济学博士",
        "en": "PhD in Economics (Yale Department of Economics, through Yale GSAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; full-time PhD only (no terminal MA); fall-only admission; classes not offered evenings/weekends",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM ET). Decisions mailed by early March; enrollment decisions due mid-April.",
        "lang": "TOEFL iBT or IELTS Academic required. TOEFL code 3987. Waiver if undergraduate degree from English-instruction institution with 3+ years residence.",
        "test": {"cls": "GRE REQUIRED. Three letters of recommendation, personal statement, transcripts. ETS code 3987; department code 0000. Scores valid 5 years."},
        "tui": "6-year full funding: 12-month stipend + fellowship covering full tuition and student healthcare. Department provides additional stipend support. Teaching fellowships in Years 3-4; research assistantships available.",
        "url": "details/yale-econ-phd.html",
    },
    {
        "id": "princeton-econ-phd",
        "s": "princeton",
        "n": "经济学博士",
        "en": "PhD in Economics (Princeton University Department of Economics)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years; coursework + general examination + dissertation; full-time residency required",
        "ddl": "Fall 2027: December 1, 2026. All applications and supporting materials due by this date. Earlier applications encouraged.",
        "lang": "TOEFL or IELTS required if native language is not English and undergraduate degree not from US/English-speaking country.",
        "test": {"cls": "GRE REQUIRED of all applicants. Institution code 2672 (no department code needed). Scores must be within 5 years. Recommended to take paper exam in October or computer-based by early December for timely receipt."},
        "tui": "No separate financial aid application needed. All admitted PhD students receive 5-year tuition support plus yearly stipend for living expenses from the Graduate School.",
        "url": "details/princeton-econ-phd.html",
    },
    {
        "id": "mit-econ-phd",
        "s": "mit",
        "n": "经济学博士",
        "en": "PhD in Economics (MIT Department of Economics)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years; 20-24 full-time students enrolled each year; core microeconomic theory, macroeconomics, econometrics; two major + two minor fields",
        "ddl": "Fall 2027: application opens September 15, 2026; deadline December 15, 2026 (11:59 PM ET). Application fee $90. Fall entry only.",
        "lang": "TOEFL iBT minimum 100 (iBT26: 5); IELTS minimum 7; Duolingo minimum 135; Cambridge English C1: 190 / C2: 200. Institute code 351.",
        "test": {"cls": "GRE REQUIRED for 2026-2027 cycle. MIT school code 3514; Economics department code 1801. Take GRE by November 30 to allow score reporting time. Writing sample (research paper) required. Three letters of recommendation, resume/CV, transcripts."},
        "tui": "Fully funded by MIT Economics: tuition, stipend, health insurance. Students work closely with faculty on theoretical and empirical research. Interdisciplinary Doctoral Program in Statistics (IDPS) affiliated.",
        "url": "details/mit-econ-phd.html",
    },
    {
        "id": "nu-econ-phd",
        "s": "nu",
        "n": "经济学博士",
        "en": "PhD in Economics (Northwestern University Department of Economics)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years (20 quarters); funded typically 5 years with attempt to support through Spring of Year 6 (23 quarters); fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM CST). Application fee $95. Program code E05PH. No winter/spring admissions.",
        "lang": "TOEFL or IELTS required for non-native English speakers. Teaching assistants must demonstrate spoken English proficiency (Versant English Test minimum 65 on arrival).",
        "test": {"cls": "GRE REQUIRED. Most successful applicants score above 90th percentile on Verbal and Quantitative Reasoning (distribution, not threshold). Dual application option with Kellogg School of Management PhD (fee increases to $175)."},
        "tui": "5-year full funding: tuition + monthly stipend + 12-month health insurance. 2026-27 minimum annual PhD stipend rate $47,748. Year 1 and dissertation year via fellowship; Years 2-4 via TA/RA.",
        "url": "details/nu-econ-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>Yes</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-econ-phd": {
        "school": "Harvard University",
        "en": "PhD in Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; core micro/macro/econometrics plus field courses; writing sample required",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM ET). Fall admission only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per GSAS policy. Harvard TOEFL code 344.",
        "test_cls": "GRE General REQUIRED. No minimum score. Minimum math preparation: calculus, linear algebra, and demonstrated proficiency with mathematics. Writing sample required (single or co-authored accepted).",
        "tui": "Fully funded by Harvard Griffin GSAS: tuition, stipend, and health fees. Department arranges campus visit weekend for all admitted students and covers a portion of visit costs.",
        "overview": "The Harvard Department of Economics has long used scholarship to address pressing questions including the future of work, ending global poverty, and improving the environment. The PhD program admits students once per year for fall entry.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE General required</li><li>Writing sample (single or co-authored accepted)</li><li>Minimum math preparation: calculus, linear algebra, proficiency with mathematics</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, CV, transcripts, letters of recommendation</li><li>Fall admission only</li></ul>",
        "research": "<ul><li>Microeconomic theory</li><li>Macroeconomics</li><li>Econometrics</li><li>Labor economics</li><li>Industrial organization</li><li>International trade and finance</li><li>Public economics</li><li>Development economics</li><li>Environmental economics</li><li>Political economy</li></ul>",
        "source": '<a href="https://gsas.harvard.edu/program/economics" target="_blank">Harvard GSAS: Economics</a> | <a href="https://economics.harvard.edu/" target="_blank">Harvard Department of Economics</a>',
    },
    "yale-econ-phd": {
        "school": "Yale University",
        "en": "PhD in Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; full-time PhD only (no terminal MA); fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM ET). Decisions mailed by early March; enrollment decisions due mid-April.",
        "lang": "TOEFL iBT or IELTS Academic required. TOEFL code 3987. Waiver if undergraduate degree from English-instruction institution with 3+ years residence.",
        "test_cls": "GRE REQUIRED. Three letters of recommendation, personal statement, transcripts. ETS code 3987; department code 0000. Scores valid 5 years.",
        "tui": "6-year full funding: 12-month stipend + fellowship covering full tuition and student healthcare. Department provides additional stipend support. Teaching fellowships in Years 3-4; research assistantships available.",
        "overview": "Yale's Department of Economics offers a full-time PhD program. Fields include microeconomics, macroeconomics, econometrics, labor, public finance, industrial organization, international trade and finance, financial economics, environmental economics, economic development, economic history, political economy, and behavioral economics.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE required</li><li>TOEFL iBT or IELTS Academic (non-native English)</li><li>3 letters of recommendation</li><li>Personal statement, transcripts</li><li>Fall admission only; no part-time/evening/weekend</li><li>Application through Yale GSAS</li></ul>",
        "research": "<ul><li>Microeconomics and macroeconomics</li><li>Econometrics and statistics</li><li>Labor and public economics</li><li>Industrial organization</li><li>International trade and finance</li><li>Financial economics</li><li>Environmental and development economics</li><li>Political economy and behavioral economics</li><li>Economic history</li></ul>",
        "source": '<a href="https://gsas.yale.edu/programs-of-study/economics" target="_blank">Yale GSAS: Economics</a> | <a href="https://economics.yale.edu/graduate/application-info" target="_blank">Yale Econ Application Procedures</a> | <a href="https://economics.yale.edu/phd-program/prospective-students" target="_blank">Prospective Students</a>',
    },
    "princeton-econ-phd": {
        "school": "Princeton University",
        "en": "PhD in Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years; coursework + general examination + dissertation; full-time residency required",
        "ddl": "Fall 2027: December 1, 2026. All applications and supporting materials due by this date.",
        "lang": "TOEFL or IELTS required if native language is not English and undergraduate degree not from US/English-speaking country.",
        "test_cls": "GRE REQUIRED of all applicants. Institution code 2672 (no department code needed). Scores must be within 5 years. Recommended to take paper exam in October or computer-based by early December.",
        "tui": "No separate financial aid application needed. All admitted PhD students receive 5-year tuition support plus yearly stipend for living expenses from the Graduate School.",
        "overview": "Princeton's Department of Economics offers a PhD program preparing students for academic and research careers. The program is known for its strength in economic theory and econometrics.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE required (institution code 2672)</li><li>TOEFL or IELTS (if applicable)</li><li>Statement of purpose, CV, transcripts</li><li>Letters of recommendation</li><li>Fall admission only; full-time residency</li><li>Earlier applications encouraged</li></ul>",
        "research": "<ul><li>Microeconomic theory</li><li>Macroeconomics</li><li>Econometrics</li><li>Game theory and decision theory</li><li>International economics</li><li>Labor economics</li><li>Public economics</li><li>Industrial organization</li><li>Financial economics</li><li>Development and agricultural economics</li></ul>",
        "source": '<a href="https://economics.princeton.edu/graduate-program/phd-admissions/common-admission-questions/" target="_blank">Princeton Econ PhD Admissions FAQ</a> | <a href="https://economics.princeton.edu/graduate-program/" target="_blank">Graduate Program</a>',
    },
    "mit-econ-phd": {
        "school": "MIT Department of Economics",
        "en": "PhD in Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years; 20-24 full-time students enrolled each year; core micro/macro/econometrics; two major + two minor fields",
        "ddl": "Fall 2027: application opens September 15, 2026; deadline December 15, 2026 (11:59 PM ET). Application fee $90. Fall entry only.",
        "lang": "TOEFL iBT minimum 100 (iBT26: 5); IELTS minimum 7; Duolingo minimum 135; Cambridge English C1: 190 / C2: 200. Institute code 351.",
        "test_cls": "GRE REQUIRED for 2026-2027 cycle. MIT school code 3514; Economics department code 1801. Take GRE by November 30 to allow score reporting time. Writing sample (research paper) required. Three letters of recommendation, resume/CV, transcripts.",
        "tui": "Fully funded by MIT Economics: tuition, stipend, health insurance. Students work closely with faculty on theoretical and empirical research. Interdisciplinary Doctoral Program in Statistics (IDPS) affiliated.",
        "overview": "MIT Economics is a top-ranked PhD program. Each year 20-24 full-time students enter. They complete core coursework in microeconomic theory, macroeconomics, and econometrics, and pursue two major and two minor fields. Graduates go on to teach in leading economics departments, business schools, and schools of public policy.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE required (MIT code 3514, dept 1801)</li><li>TOEFL 100 / IELTS 7 / Duolingo 135 / Cambridge C1 190</li><li>Writing sample (research paper)</li><li>3 letters of recommendation</li><li>Resume/CV, transcripts</li><li>$90 application fee</li><li>Fall entry only</li></ul>",
        "research": "<ul><li>Behavioral and experimental economics</li><li>Computational economics</li><li>Development economics</li><li>Econometrics</li><li>Economic history</li><li>Energy and environmental economics</li><li>Finance and financial economics</li><li>Health economics</li><li>International economics</li><li>Industrial organization</li><li>Labor economics</li><li>Macroeconomics and microeconomics</li><li>Public economics and political economy</li><li>Urban economics</li></ul>",
        "source": '<a href="https://economics.mit.edu/academic-programs/phd-program" target="_blank">MIT Econ PhD Program</a> | <a href="https://economics.mit.edu/academic-programs/phd-program/admissions" target="_blank">Admissions</a> | <a href="https://oge.mit.edu/programs/economics/" target="_blank">MIT OGE: Economics</a>',
    },
    "nu-econ-phd": {
        "school": "Northwestern University",
        "en": "PhD in Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years (20 quarters); funded typically 5 years with attempt to support through Spring of Year 6 (23 quarters); fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM CST). Application fee $95. Program code E05PH. No winter/spring admissions.",
        "lang": "TOEFL or IELTS required for non-native English speakers. Teaching assistants must demonstrate spoken English proficiency (Versant English Test minimum 65 on arrival).",
        "test_cls": "GRE REQUIRED. Most successful applicants score above 90th percentile on Verbal and Quantitative Reasoning (distribution, not threshold). Dual application option with Kellogg School of Management PhD (fee increases to $175).",
        "tui": "5-year full funding: tuition + monthly stipend + 12-month health insurance. 2026-27 minimum annual PhD stipend rate $47,748. Year 1 and dissertation year via fellowship; Years 2-4 via TA/RA.",
        "overview": "Northwestern's Department of Economics offers a PhD program with strong placement in academia and policy. The program admits for fall only. A dual application option allows students to be considered for the Kellogg School of Management PhD as a second choice.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE required (V/Q typically above 90th percentile)</li><li>TOEFL or IELTS (non-native English)</li><li>CV/resume, statement, transcripts</li><li>Letters of recommendation</li><li>$95 application fee (fee waivers available via Big Ten FreeApp for underrepresented groups)</li><li>Fall admission only</li><li>Dual Kellogg option: fee $175</li></ul>",
        "research": "<ul><li>Microeconomic theory</li><li>Macroeconomics</li><li>Econometrics</li><li>Labor economics</li><li>Industrial organization</li><li>International economics</li><li>Public economics</li><li>Development economics</li><li>Financial economics</li><li>Game theory</li></ul>",
        "source": '<a href="https://economics.northwestern.edu/graduate/prospective/admissions.html" target="_blank">Northwestern Econ Admissions</a> | <a href="https://economics.northwestern.edu/graduate/prospective/faq.html" target="_blank">FAQ</a> | <a href="https://economics.northwestern.edu/graduate/funding/departmental-funding.html" target="_blank">Departmental Funding</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"], 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)}")
