# -*- coding: utf-8 -*-
"""Round 219: batch add 5 Business School PhD Finance programs
- nyu-stern-fin-phd (NYU Stern PhD Finance)
- col-gsb-fin-phd (Columbia Business School PhD Finance)
- stanford-gsb-fin-phd (Stanford GSB PhD Finance)
- yale-som-fin-phd (Yale SOM PhD Financial Economics)
- mit-sloan-fin-phd (MIT Sloan PhD Finance)
Pattern: all top-tier business PhDs still REQUIRE GRE/GMAT with no waivers.
Reuses r214/r218 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": "nyu-stern-fin-phd",
        "s": "nyu",
        "n": "金融博士",
        "en": "PhD in Finance (NYU Stern School of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years full-time; 11-month residency per year; approximately 20-24 new students enrolled across 8 fields each year",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM ET). Fall admission only. Decisions late February through mid-April.",
        "lang": "TOEFL or IELTS required if native language is not English. TOEFL code 2586. Waiver granted if US bachelor's/master's/doctoral degree conferred by application deadline from an English-instruction institution.",
        "test": {"cls": "GRE or GMAT REQUIRED of all applicants (no waivers). Either test equally acceptable; Accounting prefers GMAT. Scores must be less than 5 years old. TOEFL/IELTS scores must be within last 2 years."},
        "tui": "All admitted doctoral students receive a 5-year financial aid package: living stipend, 100% tuition coverage, health insurance, and research/teaching assistantship opportunities. Full-time commitment; 11-month residency (September through July).",
        "url": "details/nyu-stern-fin-phd.html",
    },
    {
        "id": "col-gsb-fin-phd",
        "s": "col",
        "n": "金融博士",
        "en": "PhD in Business (Finance Division, Columbia Business School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; Year 1 core (microeconomics, econometrics, programming, finance theory I/II, pre-thesis seminar); Year 2 electives (asset pricing, corporate finance, continuous-time finance, macro, financial intermediation) + field exam; dissertation years follow.",
        "ddl": "Fall 2027: application opens September 1, 2026; submission deadline December 15, 2026. Applications received after this date are incomplete and not reviewed.",
        "lang": "TOEFL or IELTS required for international applicants unless degree earned from an institution where English was the language of instruction.",
        "test": {"cls": "GRE or GMAT REQUIRED (either accepted). No minimum score published. Essay requirement: ~1000-word statement of educational goals, research interests, and professional objectives. 2 letters of recommendation required (up to 4 accepted)."},
        "tui": "Fully funded by Columbia Business School. Acceptance rate historically under 5% of applicants. Application fee $100 (fee waivers available for US military, Peace Corps, Teach for America/China/India in service).",
        "url": "details/col-gsb-fin-phd.html",
    },
    {
        "id": "stanford-gsb-fin-phd",
        "s": "stanford",
        "n": "金融博士",
        "en": "PhD in Finance (Stanford Graduate School of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years full-time; designed to complete in 5 years, 6th year by request with continued funding",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM PST). Fall admission only. Cohort 20-25 students across all 7 fields.",
        "lang": "TOEFL iBT minimum 100; IELTS Academic minimum 7.0. Waiver if first language is English, US degree from English-instruction institution, or 2+ years consecutive professional/educational experience in English in past 10 years. Admitted students with TOEFL below 109 / IELTS below 8 must take Stanford English Placement Test.",
        "test": {"cls": "GRE or GMAT REQUIRED for all applicants regardless of prior degrees. Finance field: GRE preferred, GMAT accepted. No superscore; report all GRE scores from Dec 1, 2021 - Dec 1, 2026. GRE code 4704; GMAT code L9R-KW-27. At-home GRE and GMAT Online accepted."},
        "tui": "100% funded: tuition + health fees + living stipend. 2026-27 annual living stipend $59,500. Guaranteed 5-6 years funding with satisfactory academic progress. Conference travel and research funding included. Knight-Hennessy Scholars optional full funding for up to 3 years additional leadership program.",
        "url": "details/stanford-gsb-fin-phd.html",
    },
    {
        "id": "yale-som-fin-phd",
        "s": "yale",
        "n": "金融经济学博士",
        "en": "PhD in Financial Economics (Yale School of Management, through Yale Graduate School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-9 years; small cohort (51 total PhD students across all SOM specializations); fall-only admission; classes not offered evenings/weekends",
        "ddl": "Fall 2027: December 15, 2026. Applications through Yale Graduate School of Arts and Sciences. Considered only once per year.",
        "lang": "TOEFL required per Yale Graduate School policy. ETS code 3987. Consult SOM PhD FAQ for TOEFL waiver policy.",
        "test": {"cls": "GRE or GMAT REQUIRED (no waivers). No minimum score; admitted students typically score in high 90th percentiles: Verbal 90th percentile or greater, Quantitative 95th to 99th percentile. ETS code 3987; GMAT code 3TJ-30-78. Scores valid 5 years."},
        "tui": "All admitted students receive full financial aid for 5 years: tuition waiver + stipend comparable to leading management schools. Requires satisfactory academic progress. No evening/weekend/part-time option; full-time residency required.",
        "url": "details/yale-som-fin-phd.html",
    },
    {
        "id": "mit-sloan-fin-phd",
        "s": "mit",
        "n": "金融博士",
        "en": "PhD in Management (Finance group, MIT Sloan School of Management)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years; coursework + mandatory weekly Finance Seminar + general examination at end of Year 2 + research paper by end of 5th semester + dissertation by end of 8th semester; class size ~19 students per year across all groups",
        "ddl": "Fall 2027: December 1, 2026. Application opens September 2026. No rolling admissions. Application fee $95.",
        "lang": "TOEFL iBT minimum 90; IELTS minimum 7.0. (MIT minimum: TOEFL paper 577 / iBT 90; IELTS 7.0.) Non-native English speakers required.",
        "test": {"cls": "GMAT or GRE REQUIRED (no waivers). At-home testing allowed; unofficial score report sufficient for application, official score required upon admission. GRE code 3510; GMAT code X5X-QS-21. No minimum score, but faculty prioritize highest quantitative scores. Writing sample REQUIRED for Finance group applicants. Institute for Work & Employment Research and IT groups require GRE (GMAT not accepted)."},
        "tui": "5-year guaranteed funding: tuition, medical insurance, fellowship stipend and/or TA/RA salary, new laptop, conference travel/research budget. International students eligible. Strong quantitative background (calculator, micro/macroeconomics) required.",
        "url": "details/mit-sloan-fin-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 at a top-tier business school. 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 = {
    "nyu-stern-fin-phd": {
        "school": "NYU Stern School of Business",
        "en": "PhD in Finance",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years full-time; 11-month residency per year; approximately 20-24 new students across 8 fields each year",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM ET). Fall admission only. Decisions late February through mid-April.",
        "lang": "TOEFL or IELTS required if native language is not English. TOEFL code 2586. Waiver granted if US bachelor's/master's/doctoral degree conferred by application deadline from an English-instruction institution.",
        "test_cls": "GRE or GMAT REQUIRED of all applicants (no waivers). Either test equally acceptable; Accounting prefers GMAT. Scores must be less than 5 years old. TOEFL/IELTS scores must be within last 2 years.",
        "tui": "All admitted doctoral students receive a 5-year financial aid package: living stipend, 100% tuition coverage, health insurance, and research/teaching assistantship opportunities. Full-time commitment; 11-month residency (September through July).",
        "overview": "The NYU Stern PhD in Finance trains scholars for careers at the leading edge of financial economics. The finance faculty of more than 40 researchers (including a Nobel laureate) is consistently ranked as the leading publisher of academic research in top finance journals.",
        "requirements": "<ul><li>Bachelor's degree before Fall enrollment (all academic majors eligible)</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, CV, transcripts</li><li>Letters of recommendation</li><li>Fall admission only; 11-month residency required</li><li>Application fee (waivers available)</li></ul>",
        "research": "<ul><li>Asset pricing</li><li>Corporate finance</li><li>Derivatives and continuous-time modeling</li><li>Market microstructure</li><li>Behavioral finance</li><li>Financial intermediation and crises</li><li>Macro-finance</li><li>Empirical finance</li></ul>",
        "source": '<a href="https://www.stern.nyu.edu/programs-admissions/phd/admissions/how-to-apply" target="_blank">NYU Stern PhD How to Apply</a> | <a href="https://www.stern.nyu.edu/programs-admissions/phd/admissions/faq" target="_blank">PhD FAQ</a> | <a href="https://www.stern.nyu.edu/programs-admissions/phd/academics/fields-study/specialization-in-finance" target="_blank">Finance Specialization</a>',
    },
    "col-gsb-fin-phd": {
        "school": "Columbia Business School",
        "en": "PhD in Business (Finance Division)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; Year 1 core (microeconomics, econometrics, programming, finance theory I/II, pre-thesis seminar); Year 2 electives + field exam; dissertation years follow.",
        "ddl": "Fall 2027: application opens September 1, 2026; submission deadline December 15, 2026.",
        "lang": "TOEFL or IELTS required for international applicants unless degree earned from an institution where English was the language of instruction.",
        "test_cls": "GRE or GMAT REQUIRED (either accepted). No minimum score published. Essay requirement: ~1000-word statement of educational goals, research interests, and professional objectives. 2 letters of recommendation required (up to 4 accepted).",
        "tui": "Fully funded by Columbia Business School. Acceptance rate historically under 5% of applicants. Application fee $100 (fee waivers available for US military, Peace Corps, Teach for America/China/India in service).",
        "overview": "The Columbia Business School Finance Division PhD provides in-depth training in financial theory and quantitative methods, preparing students for high-impact academic careers. The first-year core includes microeconomics, econometrics, database/programming, finance theory, and a pre-thesis research seminar.",
        "requirements": "<ul><li>Bachelor's degree (4-year accredited); master's not required though many applicants have one</li><li>GRE or GMAT required</li><li>TOEFL or IELTS (non-native English)</li><li>~1000-word essay on educational goals, research interests, professional objectives</li><li>2 letters of recommendation (up to 4 accepted)</li><li>Application fee $100</li><li>Fall admission only; full-time study</li></ul>",
        "research": "<ul><li>Asset pricing</li><li>Corporate finance</li><li>Continuous-time finance models</li><li>Information economics</li><li>Econometric models in finance</li><li>International finance</li><li>Macro finance and banking</li><li>Financial intermediation</li></ul>",
        "source": '<a href="https://academics.business.columbia.edu/admissions/phd" target="_blank">CBS PhD Admissions</a> | <a href="https://academics.business.columbia.edu/phd/finance/admissions" target="_blank">PhD Finance Admissions</a> | <a href="https://academics.business.columbia.edu/phd/academics/finance/academics" target="_blank">Finance Academics</a>',
    },
    "stanford-gsb-fin-phd": {
        "school": "Stanford Graduate School of Business",
        "en": "PhD in Finance",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years full-time; designed to complete in 5 years, 6th year by request with continued funding",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM PST). Fall admission only. Cohort 20-25 students across all 7 fields.",
        "lang": "TOEFL iBT minimum 100; IELTS Academic minimum 7.0. Admitted students with TOEFL below 109 / IELTS below 8 must take Stanford English Placement Test.",
        "test_cls": "GRE or GMAT REQUIRED for all applicants regardless of prior degrees. Finance field: GRE preferred, GMAT accepted. No superscore; report all GRE scores. GRE code 4704; GMAT code L9R-KW-27. At-home GRE and GMAT Online accepted.",
        "tui": "100% funded: tuition + health fees + living stipend. 2026-27 annual living stipend $59,500. Guaranteed 5-6 years funding. Conference travel and research funding included. Knight-Hennessy Scholars optional.",
        "overview": "Stanford GSB offers a 5-6 year PhD program across seven fields: Accounting, Economic Analysis & Policy, Finance, Marketing, Operations Information & Technology, Organizational Behavior, and Political Economics. The program is designed to develop outstanding scholars for academic careers at leading institutions worldwide.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL iBT 100 / IELTS 7.0</li><li>Statement of purpose, CV, transcripts</li><li>Letters of recommendation</li><li>Application fee (waivers available)</li><li>May apply to Stanford GSB PhD and another Stanford program concurrently</li></ul>",
        "research": "<ul><li>Asset pricing</li><li>Corporate finance</li><li>Theoretical and empirical finance</li><li>Behavioral finance</li><li>International finance</li><li>Financial intermediation</li><li>Macroeconomics and finance</li><li>Fintech and machine learning</li></ul>",
        "source": '<a href="https://www.gsb.stanford.edu/programs/phd" target="_blank">Stanford GSB PhD Program</a> | <a href="https://www.gsb.stanford.edu/programs/phd/admission/application-materials/graduate-record-examination-gre" target="_blank">GRE Requirements</a> | <a href="https://www.gsb.stanford.edu/programs/phd/admission/application-materials/international-applicants" target="_blank">International Applicants</a>',
    },
    "yale-som-fin-phd": {
        "school": "Yale School of Management",
        "en": "PhD in Financial Economics (through Yale Graduate School of Arts and Sciences)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-9 years; small cohort (51 total PhD students across all SOM specializations); fall-only admission; classes not offered evenings/weekends",
        "ddl": "Fall 2027: December 15, 2026. Applications through Yale Graduate School of Arts and Sciences. Considered only once per year.",
        "lang": "TOEFL required per Yale Graduate School policy. ETS code 3987. Consult SOM PhD FAQ for TOEFL waiver policy.",
        "test_cls": "GRE or GMAT REQUIRED (no waivers). No minimum score; admitted students typically score in high 90th percentiles: Verbal 90th percentile or greater, Quantitative 95th to 99th percentile. ETS code 3987; GMAT code 3TJ-30-78. Scores valid 5 years.",
        "tui": "All admitted students receive full financial aid for 5 years: tuition waiver + stipend comparable to leading management schools. Requires satisfactory academic progress. No evening/weekend/part-time option.",
        "overview": "Yale SOM offers doctoral programs in Accounting, Financial Economics, Marketing, Operations, and Organizations and Management. The small program size allows senior faculty to take an active role in preparing each student for the academic job market. Applications are submitted through Yale Graduate School.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL (non-native English)</li><li>Statement of purpose, CV, transcripts</li><li>Letters of recommendation</li><li>Fall admission only; full-time study; no evening/weekend classes</li><li>Application through Yale Graduate School of Arts and Sciences</li></ul>",
        "research": "<ul><li>Asset pricing</li><li>Corporate finance</li><li>Financial econometrics</li><li>Behavioral finance</li><li>Market microstructure</li><li>International finance</li><li>Macro finance</li><li>Real estate and environmental finance</li></ul>",
        "source": '<a href="https://som.yale.edu/programs/phd" target="_blank">Yale SOM Doctoral Programs</a> | <a href="https://som.yale.edu/programs/phd/admissions" target="_blank">Admissions</a> | <a href="https://som.yale.edu/programs/phd/frequently-asked-questions" target="_blank">PhD FAQ</a>',
    },
    "mit-sloan-fin-phd": {
        "school": "MIT Sloan School of Management",
        "en": "PhD in Management (Finance group)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years; coursework + mandatory weekly Finance Seminar + general examination at end of Year 2 + research paper by end of 5th semester + dissertation by end of 8th semester; class size ~19 students per year across all groups",
        "ddl": "Fall 2027: December 1, 2026. Application opens September 2026. No rolling admissions. Application fee $95.",
        "lang": "TOEFL iBT minimum 90; IELTS minimum 7.0. Non-native English speakers required.",
        "test_cls": "GMAT or GRE REQUIRED (no waivers). At-home testing allowed; unofficial score report sufficient. GRE code 3510; GMAT code X5X-QS-21. No minimum score, but faculty prioritize highest quantitative scores. Writing sample REQUIRED for Finance group applicants.",
        "tui": "5-year guaranteed funding: tuition, medical insurance, fellowship stipend and/or TA/RA salary, new laptop, conference travel/research budget. International students eligible. Strong quantitative background required.",
        "overview": "The MIT Sloan Finance Group offers a doctoral program specialization in Finance for students interested in research careers in academic finance. The program is organized around five categories: coursework, Finance Seminar, general examination, research paper, and dissertation. Required courses 15.470-15.474 must earn a B or higher.",
        "requirements": "<ul><li>Bachelor's degree or equivalent</li><li>Strong quantitative background (calculus required for Accounting group)</li><li>Microeconomics and macroeconomics exposure</li><li>GMAT or GRE required (no waivers)</li><li>TOEFL iBT 90 / IELTS 7.0</li><li>Writing sample REQUIRED for Finance group</li><li>Resume, statement, transcripts, letters of recommendation</li><li>Application fee $95</li></ul>",
        "research": "<ul><li>Asset pricing and portfolio theory</li><li>Corporate finance</li><li>Financial econometrics</li><li>Continuous-time finance</li><li>Market microstructure</li><li>International finance</li><li>Behavioral finance</li><li>Fintech and machine learning in finance</li></ul>",
        "source": '<a href="https://mitsloan.mit.edu/programs/phd/application-information" target="_blank">MIT Sloan PhD Application Information</a> | <a href="https://mitsloan.mit.edu/faculty/academic-groups/finance/phd-program-finance" target="_blank">PhD Finance Program</a> | <a href="https://mitsloan.mit.edu/programs/phd/resources-and-faqs" target="_blank">PhD Resources and FAQs</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)}")
