# -*- coding: utf-8 -*-
"""Round 231: batch add 5 Public Health School Health Policy / HSR PhD
- yale-hpm-phd (Yale School of Public Health PhD Health Policy and Management)
- wustl-phs-phd (WashU Bursky School of Public Health PhD Public Health Sciences)
- vanderbilt-hp-phd (Vanderbilt PhD Health Policy, School of Medicine)
- emory-hsrp-phd (Emory Rollins PhD Health Services Research and Health Policy, HSRP)
- brown-hsr-phd (Brown School of Public Health PhD Health Services Research)
Key finding: GRE policy divergence persists within public health schools:
Yale HPM PhD REQUIRES GRE (one of few at YSPH), Brown HSR PhD REQUIRES GRE,
WashU PHS PhD does NOT require GRE, Vanderbilt HP PhD EXEMPT,
Emory HSRP pending department confirmation.
Deadlines: Yale/Brown/WashU Dec 1; Vanderbilt Dec 15; Emory early Dec (pending).
"""
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": "yale-hpm-phd",
        "s": "yale",
        "n": "卫生政策与管理博士",
        "en": "PhD in Health Policy and Management (Yale School of Public Health, YSPH; administered through Yale GSAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; 2 years coursework + 2-3 years dissertation; fall-only admission; 5 years of 12-month stipend + tuition support guaranteed",
        "ddl": "Fall 2027: December 1, 11:59pm ET. Application portal opens August 15. Decisions February/March.",
        "lang": "TOEFL iBT or IELTS Academic required for most non-native English speakers. ETS Yale GSAS code 3987.",
        "test": {"cls": "GRE REQUIRED (YSPH: 'GRE scores are required for PhD Biostatistics and PhD Health Policy and Management'; no minimum score, holistic review; no department code needed). ETS code 3987 (Yale GSAS). Note: YSPH does NOT accept GRE for PhD Epidemiology, Environmental Health, or Social and Behavioral Sciences."},
        "tui": "5 years of 12-month stipend + full tuition + Yale Health single-student coverage, guaranteed via YSPH fellowships, teaching fellowships, traineeships, and research assistantships.",
        "url": "details/yale-hpm-phd.html",
    },
    {
        "id": "wustl-phs-phd",
        "s": "wustl",
        "n": "公共卫生科学博士",
        "en": "PhD in Public Health Sciences (Washington University in St. Louis, Bursky School of Public Health; via SOPHAS)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "Fall admission only, one cohort per year; modified rolling review; decisions released March; requires prior master's degree in public health or related discipline",
        "ddl": "Fall 2027: December 1, 2026 (application opens September 1). Decisions released March. CGS April 15 resolution applies.",
        "lang": "English proficiency required for international applicants. WashU ETS school code 6929 (if program requires GRE).",
        "test": {"cls": "GRE NOT REQUIRED (Bursky School of Public Health: 'does not require a graduate entrance exam, such as the GRE, for admission to the PhD program'). No GRE scores considered. Holistic review. International students required to provide English proficiency test scores."},
        "tui": "Financial support for admitted PhD students (tuition + stipend + benefits). Contact Bursky SPH PhD office for current package details.",
        "url": "details/wustl-phs-phd.html",
    },
    {
        "id": "vanderbilt-hp-phd",
        "s": "vanderbilt",
        "n": "卫生政策博士",
        "en": "PhD in Health Policy (Vanderbilt University School of Medicine, Non-M.D. programs; Graduate School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "Fall-only admission; interdisciplinary social-science training in health policy; PhD programs release initial offers by March 31, response due April 15",
        "ddl": "Fall 2027: December 15, 2026 (per Vanderbilt Graduate School program matrix: Health Policy PhD, School of Medicine Non-M.D.). Application opens August 1.",
        "lang": "TOEFL iBT (minimum 89; 100 highly desired) / IELTS 7.0 / Duolingo 130 required for international applicants; waiver possible for English-language-degree holders.",
        "test": {"cls": "GRE EXEMPT (Vanderbilt Graduate School program matrix: Health Policy PhD = 'Exempt' from GRE requirement). ETS institution code 1871 (no department code needed; 0202 if required). Scores within 5 years. No minimum score; holistic review."},
        "tui": "Vanderbilt Graduate School offers substantial funding packages for PhD students (tuition + stipend + insurance). Application fee $95 for PhD programs.",
        "url": "details/vanderbilt-hp-phd.html",
    },
    {
        "id": "emory-hsrp-phd",
        "s": "emory",
        "n": "卫生服务研究与卫生政策博士",
        "en": "PhD in Health Services Research and Health Policy (HSRP, Emory Rollins School of Public Health, Department of Health Policy and Management; Laney Graduate School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "Fall-only admission; interdisciplinary with economics or political science social-science track; all admitted students receive full funding",
        "ddl": "Fall 2027: early December deadline (Laney Graduate School PhD range Dec 1 - mid-January; confirm with HSRP coordinator). Application opens for Fall 2027. Decisions by April 15 (CGS resolution).",
        "lang": "TOEFL/IELTS required per Laney Graduate School for non-native English speakers.",
        "test": {"cls": "GRE pending department confirmation (Laney Graduate School: 'it depends on which program you are applying to'; check HSRP program page). ETS code pending. No minimum score; holistic review."},
        "tui": "All admitted HSRP PhD students receive full funding (tuition + stipend + benefits). Application fee $75; limited fee waivers for prep-program participants.",
        "url": "details/emory-hsrp-phd.html",
    },
    {
        "id": "brown-hsr-phd",
        "s": "brown",
        "n": "卫生服务研究博士",
        "en": "PhD in Health Services Research (Brown University School of Public Health; via SOPHAS; optional emphasis in Pharmacoepidemiology)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "Fall-only admission; competency-based curriculum; optional emphasis in Pharmacoepidemiology; applications via SOPHAS",
        "ddl": "Fall 2027: December 1, 2026 (final deadline; 11:59pm Eastern). Application opens August 13. CGS April 15 resolution applies.",
        "lang": "TOEFL or IELTS required for international applicants; transcript evaluation if applicable. Brown SPH GRE reporting code 7765.",
        "test": {"cls": "GRE GENERAL REQUIRED (Brown Graduate Program Explorer: Health Services Research PhD = 'GRE General: Required'; GRE Subject: Not required). MCAT/LSAT cannot substitute. ETS code 7765 (Brown SPH). No minimum score; holistic review. Note: Brown BSHS PhD does NOT require GRE; Brown Biostatistics PhD also requires GRE."},
        "tui": "Funding for admitted PhD students (tuition + stipend + benefits). Contact Brown SPH HSR PhD director for current package details.",
        "url": "details/brown-hsr-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 / health services research at a top-30 U.S. school of public health. 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 department and CIP code.
</div>
</body>
</html>
"""

PAGES = {
    "yale-hpm-phd": {
        "school": "Yale School of Public Health (YSPH)",
        "en": "PhD in Health Policy and Management",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years; 2 years coursework + 2-3 years dissertation; 5 years 12-month stipend guaranteed",
        "ddl": "Fall 2027: December 1, 11:59pm ET. Portal opens August 15. Decisions Feb/March.",
        "lang": "TOEFL iBT or IELTS Academic for non-native English. ETS 3987 (Yale GSAS).",
        "test_cls": "GRE REQUIRED (YSPH HPM PhD: 'requires General GRE test scores'). ETS 3987. No minimum score; holistic. Note: YSPH does NOT accept GRE for Epi/EHS/SoBe PhDs.",
        "tui": "5 years 12-month stipend + full tuition + Yale Health single coverage (fellowships/TF/traineeships/RAs).",
        "overview": "The Yale PhD in Health Policy and Management (HPM) applies social science frameworks from economics, political science, organizational theory, management, and sociology to pressing health policy and management research questions. The program is purposefully interdisciplinary and prepares students for research careers in academia, public agencies, and private organizations. Students take qualifying exams in health policy and management, quantitative methods, and a chosen area of depth (economic theory & application; political & policy analysis; organizational theory & management), plus an individualized readings course with a faculty adviser.",
        "requirements": "<ul><li>Bachelor's degree; minimum requirement (many students already hold a master's and/or have research experience)</li><li>GRE General REQUIRED (ETS 3987; no minimum score; holistic review)</li><li>TOEFL iBT / IELTS Academic (non-native English)</li><li>Statement of purpose, CV/resume, transcripts</li><li>Letters of recommendation</li><li>No writing sample required</li><li>No need to secure a faculty mentor before applying</li><li>December 1, 11:59pm ET deadline</li><li>Fall entry only; full-time</li><li>Applications submitted through Yale GSAS (not SOPHAS)</li><li>Select 'Public Health' then Concentration: 'Health Policy and Management (PhD)'</li></ul>",
        "research": "<ul><li>Economic theory and application (health economics track)</li><li>Political and policy analysis (political science track)</li><li>Organizational theory and management (management track)</li><li>Health care organization and financing</li><li>Health policy and politics</li><li>Quantitative methods and econometrics</li><li>Cross-disciplinary work with Yale Economics, Political Science, SOM, and Law</li></ul>",
        "source": '<a href="https://ysph.yale.edu/school-of-public-health/graduate-programs/phd-degree/health-policy-management/" target="_blank">YSPH HPM PhD (Dec 1, 4-5 years, requires GRE)</a> | <a href="https://gsas.yale.edu/programs-of-study/public-health" target="_blank">Yale GSAS Public Health (GRE required for HPM PhD; ETS 3987)</a> | <a href="https://ysph.yale.edu/admissions-financial-aid/master-in-public-health-admissions/apply-to-yale-school-of-public-health/" target="_blank">YSPH GRE FAQ (required for HPM PhD; not accepted for Epi/EHS/SoBe PhDs)</a>',
    },
    "wustl-phs-phd": {
        "school": "Washington University in St. Louis, Bursky School of Public Health",
        "en": "PhD in Public Health Sciences",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "Fall admission only; one cohort/year; modified rolling; requires prior master's degree",
        "ddl": "Fall 2027: December 1, 2026. Opens September 1. Decisions March. CGS April 15.",
        "lang": "English proficiency required for international applicants. WashU ETS 6929 (if GRE required; but PhD does not require GRE).",
        "test_cls": "GRE NOT REQUIRED (Bursky SPH: 'does not require a graduate entrance exam, such as the GRE, for PhD admission'). No GRE considered. Holistic review.",
        "tui": "Financial support for admitted PhD students (tuition + stipend + benefits). Contact Bursky SPH PhD office.",
        "overview": "The Bursky School of Public Health PhD in Public Health Sciences is the doctoral program at WashU's School of Public Health. It admits one cohort per year for the fall semester, on a modified rolling basis. Applicants must already hold a master's degree or equivalent in public health or a related discipline from an accredited institution. Applications are submitted through SOPHAS, selecting 'PhD in Public Health Sciences' under Washington University in St. Louis. The program participates in the CGS April 15 resolution.",
        "requirements": "<ul><li>Master's degree or equivalent in public health or related discipline (required prior to fall enrollment)</li><li>GRE NOT required (no scores considered)</li><li>English proficiency test (international applicants)</li><li>SOPHAS application (select PhD in Public Health Sciences, WashU)</li><li>Official transcripts</li><li>CV/resume</li><li>Personal statement</li><li>One writing sample</li><li>Three letters of recommendation</li><li>December 1, 2026 deadline (modified rolling; apply early)</li><li>Fall entry only; full-time</li></ul>",
        "research": "<ul><li>Public health sciences across the Bursky SPH departments</li><li>Health services research</li><li>Epidemiology</li><li>Biostatistics</li><li>Health policy</li><li>Social and behavioral health sciences</li><li>Cross-disciplinary work with WashU School of Medicine and Barnes-Jewish Hospital</li></ul>",
        "source": '<a href="https://publichealth.washu.edu/admissions/apply-phd/" target="_blank">WashU Bursky PhD (Dec 1, GRE not required, master\'s required, SOPHAS)</a> | <a href="https://bulletin.wustl.edu/publichealth/admissions/" target="_blank">WashU Bulletin SPH Admissions (doctoral requirements: writing sample, 3 recs, SOPHAS)</a>',
    },
    "vanderbilt-hp-phd": {
        "school": "Vanderbilt University School of Medicine",
        "en": "PhD in Health Policy",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "Fall-only; social-science interdisciplinary training; offers by March 31, response April 15",
        "ddl": "Fall 2027: December 15, 2026 (per Vanderbilt Graduate School program matrix). Opens August 1.",
        "lang": "TOEFL iBT 89 min (100 desired) / IELTS 7.0 / Duolingo 130 for international; waiver for English-degree holders.",
        "test_cls": "GRE EXEMPT (Vanderbilt Graduate School matrix: Health Policy PhD = 'Exempt'). ETS 1871 (no dept code; 0202 if required). No minimum; holistic.",
        "tui": "Vanderbilt Graduate School PhD funding package (tuition + stipend + insurance). Application fee $95.",
        "overview": "The Vanderbilt PhD in Health Policy is offered through the Graduate School under the School of Medicine Non-M.D. portfolio, alongside Epidemiology PhD, Hearing and Speech Sciences PhD, and the MSTP MD/PhD. The program applies social-science and analytical training to health policy and health services research questions. The Graduate School program matrix explicitly lists Health Policy PhD as GRE-Exempt, with a December 15 deadline (later than the December 1 typical for many other Vanderbilt PhD programs).",
        "requirements": "<ul><li>Bachelor's degree or equivalent from regionally accredited institution (international degree evaluation recommended)</li><li>GRE EXEMPT (no scores required)</li><li>TOEFL 89 / IELTS 7.0 / Duolingo 130 (international; waiver possible)</li><li>Vanderbilt Graduate School online application</li><li>Transcripts, CV, statement of purpose</li><li>Letters of recommendation</li><li>December 15, 2026 deadline</li><li>Fall entry only; full-time</li><li>Application fee $95 for PhD; fee waivers available</li><li>May apply to up to 2 programs per term</li></ul>",
        "research": "<ul><li>Health policy and politics</li><li>Health economics and financing</li><li>Health services research</li><li>Health care organization and management</li><li>Cross-disciplinary work with Vanderbilt School of Medicine, Owen Graduate School of Management, and Law School</li></ul>",
        "source": '<a href="https://gradschool.vanderbilt.edu/admissions/apply/application-requirements-by-program/" target="_blank">Vanderbilt Graduate School Program Matrix (Health Policy PhD: Exempt, Dec 15)</a> | <a href="https://gradschool.vanderbilt.edu/application-requirements/" target="_blank">Vanderbilt Application Requirements (ETS 1871, scores within 5 years)</a> | <a href="https://gradschool.vanderbilt.edu/application-faqs/" target="_blank">Vanderbilt FAQ ($95 PhD fee; 2 programs/term)</a>',
    },
    "emory-hsrp-phd": {
        "school": "Emory Rollins School of Public Health",
        "en": "PhD in Health Services Research and Health Policy (HSRP)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "Fall-only; interdisciplinary with economics OR political science social-science track; all admitted students fully funded",
        "ddl": "Fall 2027: early December (Laney Graduate School PhD range Dec 1 - mid-January; confirm with HSRP coordinator). Decisions by April 15 (CGS).",
        "lang": "TOEFL/IELTS per Laney Graduate School for non-native English speakers.",
        "test_cls": "GRE pending department confirmation (LGS: 'it depends on which program you are applying to'). Check HSRP program page. No minimum; holistic.",
        "tui": "All admitted HSRP PhD students receive full funding (tuition + stipend + benefits). Application fee $75; limited fee waivers.",
        "overview": "Emory's Health Services Research and Health Policy (HSRP) PhD is housed in the Rollins School of Public Health's Department of Health Policy and Management (ranked #5 nationally by U.S. News). It combines an interdisciplinary, policy-oriented public health approach with rigorous social-science training in either economics or political science. The program trains future researchers and policy analysts for academia, industry, research and consulting organizations, government, and non-profits. It is closely aligned with Emory's Center on Health Outcomes and Quality and the Institute for Advanced Policy Solutions. All admitted PhD students receive full funding.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative/social-science preparation</li><li>GRE pending department confirmation (LGS policy varies by program)</li><li>TOEFL/IELTS (non-native English)</li><li>Laney Graduate School online application</li><li>Resume/CV, statement of purpose, transcripts</li><li>Writing sample (if applicable)</li><li>Letters of recommendation (contact info with institutional affiliation)</li><li>Early December deadline (confirm with HSRP coordinator)</li><li>Fall entry only; full-time</li><li>Select economics OR political science track on application</li><li>Application fee $75; fee waivers for prep-program participants</li></ul>",
        "research": "<ul><li>Health economics and econometrics (economics track)</li><li>Health policy and politics (political science track)</li><li>Health care management and financing</li><li>Cost-effectiveness analysis</li><li>Policy analysis and evaluation</li><li>Health disparities and social determinants</li><li>Chronic conditions and obesity costs</li><li>Cardiac care outcomes measurement</li><li>Health insurance markets and reform (U.S. and Europe)</li><li>Cancer screening impact</li><li>Cross-disciplinary work with Emory Economics, Rollins, CDC, and Georgia DPH</li></ul>",
        "source": '<a href="https://web.gs.emory.edu/degree-programs/" target="_blank">Emory LGS: Health Services Research and Health Policy PhD (HSRP; full funding; econ/poli-sci track)</a> | <a href="https://gs.emory.edu/admissions/application.html" target="_blank">Emory LGS Application (fee $75; materials; Fall 2027 open)</a> | <a href="https://gs.emory.edu/admissions/faq" target="_blank">Emory LGS FAQ (deadlines Dec 1 - mid-Jan; GRE depends on program)</a>',
    },
    "brown-hsr-phd": {
        "school": "Brown University School of Public Health",
        "en": "PhD in Health Services Research",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "Fall-only; competency-based curriculum; optional emphasis in Pharmacoepidemiology; via SOPHAS",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm Eastern). Opens August 13. CGS April 15.",
        "lang": "TOEFL/IELTS for international; transcript evaluation if applicable. Brown SPH GRE code 7765.",
        "test_cls": "GRE GENERAL REQUIRED (Brown Program Explorer: HSR PhD = 'GRE General: Required'; Subject: Not required). MCAT/LSAT cannot substitute. ETS 7765. No minimum; holistic. Note: Brown BSHS PhD does NOT require GRE; Brown Biostat PhD also requires GRE.",
        "tui": "Funding for admitted PhD students (tuition + stipend + benefits). Contact Brown SPH HSR PhD director.",
        "overview": "The Brown PhD in Health Services Research (HSR) trains students in research methods to advance population health, focusing on organizational characteristics of health care delivery systems, providers, and economic forces that shape consumer and provider behavior, plus the policy environment. The competency-based curriculum provides a strong analytic foundation and general HSR orientation. Students may select an emphasis area in Pharmacoepidemiology. Applications are submitted through SOPHAS. The Brown Graduate Program Explorer explicitly lists HSR PhD as requiring the GRE General Test.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative preparation</li><li>GRE General REQUIRED (ETS 7765; Subject not required; MCAT/LSAT cannot substitute)</li><li>TOEFL/IELTS (international); transcript evaluation if applicable</li><li>SOPHAS application (select Health Services Research PhD, Brown)</li><li>Official transcripts</li><li>Personal statement</li><li>CV/resume</li><li>Three letters of recommendation</li><li>Application fee</li><li>December 1, 2026 deadline (11:59pm Eastern)</li><li>Fall entry only; full-time</li><li>Optional emphasis in Pharmacoepidemiology</li></ul>",
        "research": "<ul><li>Health care delivery systems and organizations</li><li>Provider behavior and economic forces</li><li>Consumer behavior and policy environment</li><li>Pharmacoepidemiology (optional emphasis)</li><li>Population health and outcomes</li><li>Health services research methods</li><li>Cross-disciplinary work with Brown Alpert Medical School, School of Public Health, and CDC</li></ul>",
        "source": '<a href="https://graduateprograms.brown.edu/graduate-program/health-services-research-phd" target="_blank">Brown HSR PhD (Dec 1, 2026; GRE General required; SOPHAS; Pharmacoepi emphasis)</a> | <a href="https://apply.graduateschool.brown.edu/portal/program_explorer" target="_blank">Brown Graduate Program Explorer (HSR PhD deadline Dec 1; opens Aug 13)</a> | <a href="https://sph.brown.edu/admission-aid/application-deadlines" target="_blank">Brown SPH Deadlines (HSR PhD Dec 1; Biostat PhD Dec 1; BSHS PhD Nov 15)</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)}")
