# -*- coding: utf-8 -*-
"""Round 229: batch add 5 Health Policy / Accounting PhD
- up-wharton-hcmg-phd (Wharton PhD Health Care Management & Economics)
- harvard-health-policy-phd (Harvard PhD Health Policy, Management concentration)
- duke-fuqua-accounting-phd (Duke Fuqua PhD Business Administration - Accounting)
- cornell-johnson-accounting-phd (Cornell Johnson PhD Management - Accounting)
- stanford-health-policy-phd (Stanford PhD Health Policy, FSI)
Key finding: Harvard Health Policy Management track requires GRE/GMAT (other tracks optional);
Stanford Health Policy reinstated GRE requirement for 2027-28;
Duke Fuqua CIP 52.1399 STEM eligible;
Wharton HCMG accepts college grads regardless of major incl. clinically trained professionals.
Deadlines: Dec 1 (Harvard, Stanford) vs Dec 14 (Duke) vs Dec 15 (Wharton, Cornell).
All fully funded.
"""
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": "up-wharton-hcmg-phd",
        "s": "up",
        "n": "医疗保健管理与经济学博士",
        "en": "PhD in Health Care Management & Economics (The Wharton School, University of Pennsylvania)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; fall-only admission; Wharton admits students for full-time study only beginning in the fall semester",
        "ddl": "Fall 2027: December 15, 2026 (11:59PM EST). On-campus interviews in February; final decisions by March. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Wharton doctoral admissions.",
        "test": {"cls": "GRE or GMAT required (Wharton doctoral program requires ALL applicants to take and provide scores for either GMAT or GRE; test requirements vary by program per Wharton field table). ETS code 2926 (Wharton). No minimum score. Fall 2026 entering cohort average: GRE V160 / Q169 (distribution, not minimum threshold)."},
        "tui": "All Wharton doctoral students receive a full fellowship that covers tuition expenses and includes a living stipend, plus health insurance.",
        "url": "details/up-wharton-hcmg-phd.html",
    },
    {
        "id": "harvard-health-policy-phd",
        "s": "harvard",
        "n": "卫生政策博士",
        "en": "PhD in Health Policy (Harvard Griffin GSAS; interdisciplinary across Harvard Kennedy School, Harvard T.H. Chan School of Public Health, Harvard Medical School, and Harvard Faculty of Arts and Sciences)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years full-time; fall-only admission; applicants must apply to a specific concentration (up to two); concentrations include Decision Sciences, Economics, Management, Methods for Policy Research, Political Analysis",
        "ddl": "Fall 2027: December 1, 2026 (5:00pm Boston time). Admissions decisions by beginning of March. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Harvard GSAS.",
        "test": {"cls": "GRE or GMAT REQUIRED for the Management concentration (regardless of academic/professional background; program prefers GRE but also accepts GMAT). Standardized tests are OPTIONAL for Decision Sciences, Economics, Methods for Policy Research, and Political Analysis tracks. ETS code 3451 (Harvard Griffin GSAS). No minimum score; generally successful applicants score above the 80th percentile (distribution, not minimum)."},
        "tui": "Full funding through Harvard Griffin GSAS: tuition + stipend + health insurance for all admitted PhD students.",
        "url": "details/harvard-health-policy-phd.html",
    },
    {
        "id": "duke-fuqua-accounting-phd",
        "s": "duke",
        "n": "工商管理博士（会计方向）",
        "en": "PhD in Business Administration - Accounting (Fuqua School of Business, Duke University; CIP 52.1399)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years full-time; each academic area matriculates 2-3 students per year; flexible cross-registration at UNC-Chapel Hill and NC State; fall-only admission",
        "ddl": "Fall 2027: December 14, 2026 (11:59:59pm EST). Fall entry only.",
        "lang": "TOEFL, IELTS, or Duolingo English Test required for applicants whose first language is not English (waiver may apply).",
        "test": {"cls": "GRE or GMAT required (GMAT accepted in lieu of GRE; GRE CANNOT be waived under any circumstance). No minimum score. Acceptance rate ranges 2%-8% across Fuqua PhD areas (distribution, not minimum)."},
        "tui": "Full funding package for admitted PhD students (tuition + stipend + health insurance).",
        "url": "details/duke-fuqua-accounting-phd.html",
    },
    {
        "id": "cornell-johnson-accounting-phd",
        "s": "cornell",
        "n": "管理博士（会计方向）",
        "en": "PhD in Management - Accounting (Samuel Curtis Johnson Graduate School of Management, Cornell SC Johnson College of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years full-time; residential in Ithaca, NY; fully funded; fall-only admission; one of the main faculty areas (Applied Economics & Policy, Accounting, Finance, Management & Organizations)",
        "ddl": "Fall 2027: December 15, 2026. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Cornell Graduate School.",
        "test": {"cls": "GRE General or GMAT required (GMAT Focus Edition accepted). ETS code 2098 (Cornell Graduate School; no department code needed; use 0000 undecided if prompted); GMAT code 5JW-BM-26. GRE scores valid 5 years. No minimum score. Math preparation through calculus is essential."},
        "tui": "Fully funded: tuition waiver + stipend for living expenses. PhD students are supported by research and teaching assistantships.",
        "url": "details/cornell-johnson-accounting-phd.html",
    },
    {
        "id": "stanford-health-policy-phd",
        "s": "stanford",
        "n": "卫生政策博士",
        "en": "PhD in Health Policy (Stanford Health Policy, Freeman Spogli Institute for International Studies; HRP-PHD)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years full-time; interdisciplinary with Stanford School of Medicine, Graduate School of Business, Department of Economics, and Stanford Law School; fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm Pacific Time) for 2027-2028 cycle. Knight-Hennessy Scholars deadline earlier: October 6, 2026 (1:00pm PT). Fall entry only.",
        "lang": "TOEFL or IELTS required per Stanford graduate admissions.",
        "test": {"cls": "GRE REQUIRED for the 2027-2028 application cycle (per Stanford Health Policy: GRE will be required for 2027-2028; this may change in future years). ETS code 4704 (Stanford University; department code unspecified). Note: program is quantitatively based and a strong mathematical foundation is necessary. No minimum score."},
        "tui": "Full funding through Stanford Health Policy / Knight-Hennessy Scholars (up to 3 years of funding). IMPORTANT CAVEAT: per Stanford Health Policy website, 'due to ongoing uncertainties in the funding of academic institutions, our capacity to admit a full cohort of PhD students may be limited; admissions will depend on availability of funding.' Applicants strongly advised to pursue external fellowships.",
        "url": "details/stanford-health-policy-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 health policy / accounting. Admitted PhD students receive full financial support. Admission statistics shown are distribution ranges, not minimum thresholds. Course/credit details pending department bulletin verification. STEM designation status per CIP code and department confirmation.
</div>
</body>
</html>
"""

PAGES = {
    "up-wharton-hcmg-phd": {
        "school": "The Wharton School, University of Pennsylvania",
        "en": "PhD in Health Care Management & Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years full-time; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59PM EST). On-campus interviews February; decisions by March.",
        "lang": "TOEFL/IELTS required for non-native English speakers per Wharton doctoral admissions.",
        "test_cls": "GRE or GMAT required (Wharton requires all doctoral applicants to take either GMAT or GRE). ETS 2926. No minimum score. Fall 2026 entering avg GRE V160/Q169 (distribution, not minimum).",
        "tui": "Full fellowship covering tuition + living stipend + health insurance for all admitted doctoral students.",
        "overview": "Wharton PhD in Health Care Management & Economics (HCMG) trains scholars who apply economics, management, finance, and policy analysis to the health care sector. The program welcomes applicants from diverse backgrounds: college graduates regardless of major, MBA/MPH/MA/MS post-baccalaureate graduates in health care or social science, and clinically trained professionals (physicians, nurses, dentists, medical students). The HCMG department is jointly housed at Wharton and the University of Pennsylvania Perelman School of Medicine, with cross-registration at Penn's medical and public health schools.",
        "requirements": "<ul><li>Bachelor's degree or higher; any major considered</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL/IELTS (non-native English)</li><li>Statement of purpose, transcripts, CV</li><li>3 letters of recommendation</li><li>December 15, 2026 11:59PM EST deadline</li><li>Fall entry only; full-time study</li><li>On-campus interviews in February for selected students</li><li>No minimum test score; holistic review</li><li>Clinically trained professionals (MD/MD candidates) encouraged to apply</li></ul>",
        "research": "<ul><li>Health economics and health care financing</li><li>Health insurance and public insurance programs (Medicare/Medicaid)</li><li>Health care organization and management</li><li>Pharmaceutical economics and policy</li><li>Health labor markets (physicians, nurses)</li><li>Health technology assessment and cost-effectiveness</li><li>Global health and health systems</li><li>Cross-disciplinary work with Penn Medicine and Penn Nursing</li></ul>",
        "source": '<a href="https://hcmg.wharton.upenn.edu/programs/phd/admissions/" target="_blank">Wharton HCMG PhD Admissions</a> | <a href="https://doctoral.wharton.upenn.edu/application-requirements/" target="_blank">Wharton Doctoral Application Requirements</a> | <a href="https://doctoral.wharton.upenn.edu/overview/facts-and-dates/" target="_blank">Facts & Dates (Dec 15 deadline, full fellowship)</a>',
    },
    "harvard-health-policy-phd": {
        "school": "Harvard Griffin Graduate School of Arts and Sciences",
        "en": "PhD in Health Policy (interdisciplinary)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5 years full-time; fall-only admission; applicants apply to a specific concentration (up to two)",
        "ddl": "Fall 2027: December 1, 2026 (5:00pm Boston time). Decisions by beginning of March.",
        "lang": "TOEFL/IELTS required for non-native English speakers per Harvard GSAS.",
        "test_cls": "GRE or GMAT REQUIRED for Management concentration (program prefers GRE but also accepts GMAT). Standardized tests OPTIONAL for Decision Sciences, Economics, Methods for Policy Research, Political Analysis. ETS 3451. No minimum score; generally successful applicants above 80th percentile (distribution, not minimum).",
        "tui": "Full funding through Harvard Griffin GSAS: tuition + stipend + health insurance.",
        "overview": "Harvard PhD in Health Policy is an interdisciplinary degree granted by Harvard Griffin GSAS, jointly administered across Harvard Kennedy School, Harvard T.H. Chan School of Public Health, Harvard Medical School, and the Harvard Faculty of Arts and Sciences. Students apply to one of five concentrations: Decision Sciences, Economics, Management, Methods for Policy Research, or Political Analysis. The Management concentration (which students often pursue through Harvard Business School faculty) is the only track that still requires GRE/GMAT; all other tracks have gone test-optional as of the 2023-2024 application season.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative/social science preparation</li><li>GRE or GMAT required for Management concentration (optional for other tracks)</li><li>TOEFL/IELTS (non-native English)</li><li>Statement of purpose, personal statement, resume/CV, transcripts</li><li>3 letters of recommendation</li><li>December 1, 2026 5pm EST deadline</li><li>Fall entry only; must specify concentration in SOP (up to two)</li><li>Applications reviewed by both concentration faculty and general admissions committee</li><li>No minimum score; holistic review</li></ul>",
        "research": "<ul><li>Health economics and econometrics (Economics track)</li><li>Health care decision sciences and medical decision making (Decision Sciences track)</li><li>Health care management and organizational behavior (Management track)</li><li>Political analysis of health policy and the politics of health reform (Political Analysis track)</li><li>Methods for policy research (statistical methods, causal inference)</li><li>Health care financing and insurance</li><li>Global health policy</li><li>Cross-disciplinary work across HKS, HSPH, HMS, and FAS</li></ul>",
        "source": '<a href="https://healthpolicy.fas.harvard.edu/frequently-asked-questions" target="_blank">Harvard Health Policy PhD FAQ (GRE by concentration)</a> | <a href="https://healthpolicy.fas.harvard.edu/apply" target="_blank">Apply (Dec 1, 5pm EST)</a> | <a href="https://gsas.harvard.edu/programs" target="_blank">Harvard GSAS Programs (Health Policy GRE optional)</a>',
    },
    "duke-fuqua-accounting-phd": {
        "school": "Duke University Fuqua School of Business",
        "en": "PhD in Business Administration - Accounting",
        "deg": "Doctor of Philosophy (PhD, CIP 52.1399)",
        "stem_label": "STEM-eligible (CIP 52.1399 per Fuqua PhD page)",
        "dur": "5 years full-time; each academic area matriculates 2-3 students/year; cross-registration at UNC-Chapel Hill and NC State",
        "ddl": "Fall 2027: December 14, 2026 (11:59:59pm EST). Fall entry only.",
        "lang": "TOEFL/IELTS/Duolingo English Test required for non-native English speakers (waiver may apply).",
        "test_cls": "GRE or GMAT required (GMAT accepted in lieu of GRE; CANNOT be waived under any circumstance). No minimum score. Fuqua PhD acceptance rate 2%-8% across areas (distribution, not minimum).",
        "tui": "Full funding package for admitted PhD students (tuition + stipend + health insurance).",
        "overview": "Duke Fuqua PhD in Business Administration is a research doctorate (CIP 52.1399, STEM-eligible) with seven academic areas: accounting, decision sciences, finance, management and organizations, marketing, operations management, and strategy. The Accounting area requires a minimum of 15 PhD-level courses, two research papers (first-year summer paper and second-year curriculum paper), qualifying exams in empirical and analytical accounting research, a teaching apprenticeship, and a dissertation defense. Students take advantage of Fuqua's collaborative culture with co-authored faculty research and cross-registration at UNC-Chapel Hill.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative preparation</li><li>GRE or GMAT required (no waivers under any circumstance)</li><li>TOEFL/IELTS/Duolingo (non-native English; waiver may apply)</li><li>Statement of purpose, transcripts, resume/CV</li><li>3 letters of recommendation</li><li>Writing sample: none required</li><li>December 14, 2026 11:59:59pm EST deadline</li><li>Fall entry only; full-time</li><li>Each area matriculates 2-3 students per year</li><li>15 PhD-level courses required; 2 research papers; qualifying exams; dissertation</li></ul>",
        "research": "<ul><li>Empirical archival financial accounting research</li><li>Analytical/structural accounting theory</li><li>Agency theory and information economics in accounting</li><li>Current topics and methods in accounting research</li><li>Microeconomics and econometrics (2 PhD courses each)</li><li>Finance (2 PhD courses)</li><li>Cross-disciplinary electives at Duke Economics, UNC-Chapel Hill, NC State</li><li>Teaching apprenticeship and research assistant work</li></ul>",
        "source": '<a href="https://www.fuqua.duke.edu/programs/phd" target="_blank">Duke Fuqua PhD (CIP 52.1399 STEM-eligible, Dec 14 deadline, GRE no waiver)</a> | <a href="https://gradschool.duke.edu/academics/programs-degrees/business-administration/" target="_blank">Duke Graduate School PhD Business Administration</a> | <a href="https://areas.fuqua.duke.edu/accounting/ph-d-program/curriculum-program-requirements/" target="_blank">Accounting Curriculum Requirements</a>',
    },
    "cornell-johnson-accounting-phd": {
        "school": "Cornell SC Johnson College of Business (Johnson)",
        "en": "PhD in Management - Accounting",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5 years full-time; residential in Ithaca, NY; fully funded; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Fall entry only.",
        "lang": "TOEFL/IELTS required per Cornell Graduate School English proficiency requirement.",
        "test_cls": "GRE General or GMAT required (GMAT Focus Edition accepted). ETS 2098 (Cornell Graduate School; no department code needed; use 0000 undecided if prompted); GMAT 5JW-BM-26. GRE valid 5 years. No minimum score. Math preparation through calculus is essential.",
        "tui": "Fully funded: tuition waiver + stipend for living expenses. Supported by research and teaching assistantships.",
        "overview": "Cornell Johnson PhD in Management is a research-focused degree within the Cornell SC Johnson College of Business, offered in four main faculty areas: Applied Economics and Policy, Accounting, Finance, and Management and Organizations. The Accounting concentration examines how firms report information to investors, how accounting information is used to manage firms, and the nature of auditing. The program is residential in Ithaca, NY, and admits students directly from bachelor's degree programs (an MBA or master's is not required). Students may be admitted directly from a bachelor's or after a distinguished record in an MBA or other master's program.",
        "requirements": "<ul><li>Bachelor's degree; strong undergraduate work in economics, engineering, mathematics, operations research, psychology, sociology, or another physical/social science</li><li>GRE General or GMAT required (GMAT Focus accepted)</li><li>TOEFL/IELTS (non-native English)</li><li>Statement of purpose, personal statement, transcripts</li><li>2 letters of recommendation</li><li>Math preparation through calculus is essential</li><li>December 15, 2026 deadline</li><li>Fall entry only; residential in Ithaca, NY</li><li>MBA or master's degree not required</li><li>Note: applicants interested in Strategy and Business Economics should apply to the Graduate Field of Economics, not Management</li></ul>",
        "research": "<ul><li>How firms report financial information to investors</li><li>Use of accounting information in firm management</li><li>Nature of auditing and audit markets</li><li>Equity valuation and earnings announcements</li><li>Non-GAAP reporting and forces shaping accounting fundamentals</li><li>Financial market regulation and investor welfare</li><li>Management accounting and firms' choice of accounting policies</li><li>Corporate social responsibility and accounting</li></ul>",
        "source": '<a href="https://courses.cornell.edu/programs/management-phd/" target="_blank">Cornell Catalog Management PhD (Dec 15, GRE or GMAT, ETS 2098)</a> | <a href="https://www.johnson.cornell.edu/programs/phd-program/admissions/" target="_blank">Cornell Johnson PhD Admissions (GMAT 5JW-BM-26)</a> | <a href="https://gradschool.cornell.edu/admissions/application-steps/required-tests/" target="_blank">Cornell Graduate School Required Tests</a>',
    },
    "stanford-health-policy-phd": {
        "school": "Stanford University Freeman Spogli Institute for International Studies",
        "en": "PhD in Health Policy (HRP-PHD)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5-6 years full-time; interdisciplinary with Stanford School of Medicine, GSB, Economics, and Law; fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm Pacific Time) for 2027-2028 cycle. Knight-Hennessy Scholars deadline: October 6, 2026 (1:00pm PT). Fall entry only.",
        "lang": "TOEFL/IELTS required per Stanford graduate admissions.",
        "test_cls": "GRE REQUIRED for 2027-2028 application cycle (per Stanford Health Policy: GRE will be required for 2027-2028; may change in future years). ETS 4704 (Stanford; department code unspecified). Program is quantitatively based; strong mathematical foundation necessary. No minimum score. U.S.-licensed physicians may substitute MCAT for GRE in MS program but not PhD.",
        "tui": "Full funding through Stanford Health Policy and/or Knight-Hennessy Scholars (up to 3 years KHS funding). CAVEAT: per Stanford Health Policy website, capacity to admit a full cohort may be limited due to ongoing funding uncertainties; admissions depend on availability of funding. Applicants strongly advised to pursue external fellowships.",
        "overview": "Stanford PhD in Health Policy (HRP-PHD, Freeman Spogli Institute) trains scholarly leaders who will become experts in the theoretical and empirical approaches applied to improve health policy and the health care system. The curriculum spans health economics, health insurance and government program operation, health financing, international health policy and economic development, cost-effectiveness analysis and evaluation of new technologies, health law and ethics, health systems operations, and relevant statistical and methodological approaches. The program is interdisciplinary across Stanford School of Medicine, Graduate School of Business, Department of Economics, and Stanford Law School.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative preparation</li><li>GRE required for 2027-2028 cycle (reinstated; may change future years)</li><li>TOEFL/IELTS (non-native English)</li><li>Statement of purpose, CV with work and research experience, transcripts</li><li>Letters of recommendation</li><li>December 1, 2026 11:59pm PT deadline</li><li>Fall entry only; quantitatively based program</li><li>Strong mathematical foundation necessary</li><li>Knight-Hennessy Scholars available (separate application, earlier deadline Oct 6, 2026)</li><li>NOTE: limited cohort capacity due to funding uncertainties -- apply early and pursue external fellowships</li></ul>",
        "research": "<ul><li>Health economics and financing</li><li>Health insurance and government health programs (Medicare/Medicaid)</li><li>International health policy and economic development</li><li>Cost-effectiveness analysis and health technology assessment</li><li>Health law and ethics</li><li>Health systems operations and management</li><li>Statistical and methodological approaches to health research</li><li>Health policy issues related to obesity and chronic disease</li><li>Cross-disciplinary work with Stanford Medicine, GSB, Economics, and Law</li></ul>",
        "source": '<a href="https://healthpolicy.fsi.stanford.edu/content/phd-hsr-application" target="_blank">Stanford Health Policy PhD Application (Dec 1, 2026 11:59pm PT, GRE required 2027-28)</a> | <a href="https://healthpolicy.fsi.stanford.edu/content/phd-health-policy" target="_blank">PhD in Health Policy Overview (funding caveat)</a> | <a href="https://bulletin.stanford.edu/programs/HRP-PHD" target="_blank">Stanford Bulletin HRP-PHD</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)}")
