# -*- coding: utf-8 -*-
"""Round 218: batch add 5 PhDs - Finance and Statistics
- uchicago-booth-fin-phd (Chicago Booth Stevens Doctoral Program, Finance)
- upenn-wharton-fin-phd (Wharton PhD Finance)
- upenn-wharton-stats-phd (Wharton PhD Statistics and Data Science)
- cmu-stat-phd (CMU Statistics PhD)
- berkeley-stat-phd (UC Berkeley Statistics PhD)
Key: Booth and Wharton still REQUIRE GRE/GMAT (business PhDs holdout).
CMU Statistics is GRE-optional. Berkeley Statistics no longer accepts GRE at all.
Reuses r214 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": "uchicago-booth-fin-phd",
        "s": "uchicago",
        "n": "金融博士（Stevens项目）",
        "en": "PhD in Finance (Stevens Doctoral Program, Chicago Booth)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; approximately 20-25 students enter the Stevens Program each year",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM PST). Applications open early September. Decisions on or before April 15.",
        "lang": "TOEFL iBT minimum 5 overall and 5 in each subsection (for tests taken on or after January 21, 2026); IELTS minimum 7.0 overall with 7.0 in each subsection. TOEFL code 1819.",
        "test": {"cls": "GRE/GMAT REQUIRED of all applicants (no exceptions, even with prior graduate degrees). Finance: GRE strongly preferred, GMAT acceptable. No minimum cutoff; average GRE Quant for incoming students is 168. GRE code 1501; GMAT code H9X-9F-05. Recommended to take test by early October. Joint Program in Financial Economics (with UChicago Economics) requires GRE."},
        "tui": "Fully funded: tuition grant, stipend, student health insurance, computer or computer subsidy, and access to research and travel funding. 2026-27 admitted class profile: average GPA 3.91, average GRE Quant 168, average TOEFL 109, average age 24, 18 countries represented, 52% entering with an advanced degree.",
        "url": "details/uchicago-booth-fin-phd.html",
    },
    {
        "id": "upenn-wharton-fin-phd",
        "s": "up",
        "n": "金融博士",
        "en": "PhD in Finance (Wharton School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; coursework + preliminary written/oral exam + dissertation proposal and defense; many programs require a preliminary research paper",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM EST). Fall admission only. Decisions on or before April 15.",
        "lang": "TOEFL or IELTS required for non-native English speakers. High level of proficiency expected.",
        "test": {"cls": "GRE or GMAT REQUIRED (Finance: GRE or GMAT accepted; no waivers). No minimum score, but accepted applicants typically fall within the top 10 percent. Average GRE for fall 2026 entrants: Verbal 160 (80th percentile), Quantitative 169 (87th), Writing 4.2 (68th). Average GMAT: V 90th, Q 97th, Total 735 (100th). GRE code 2954-5199; GMAT code G56-97-12. Tests must be taken by December 15."},
        "tui": "All admitted students receive a FULL FELLOWSHIP including stipend, tuition coverage, and health insurance. Wharton Doctoral Programs admits for full-time study only beginning in the fall semester.",
        "url": "details/upenn-wharton-fin-phd.html",
    },
    {
        "id": "upenn-wharton-stats-phd",
        "s": "up",
        "n": "统计与数据科学博士",
        "en": "PhD in Statistics and Data Science (Wharton School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; coursework + preliminary written/oral exam + dissertation proposal and defense",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM EST). Fall admission only. Decisions on or before April 15.",
        "lang": "TOEFL or IELTS required for non-native English speakers. High level of proficiency expected.",
        "test": {"cls": "GRE ONLY (Statistics and Data Science program accepts GRE only; GMAT not accepted). No minimum score, but accepted applicants typically fall within the top 10 percent. Average GRE for fall 2026 entrants: Verbal 160 (80th), Quantitative 169 (87th), Writing 4.2 (68th). GRE code 2954-5199. Tests must be taken by December 15."},
        "tui": "All admitted students receive a FULL FELLOWSHIP including stipend, tuition coverage, and health insurance. Wharton Doctoral Programs admits for full-time study only beginning in the fall semester.",
        "url": "details/upenn-wharton-stats-phd.html",
    },
    {
        "id": "cmu-stat-phd",
        "s": "cmu",
        "n": "统计学博士",
        "en": "PhD in Statistics (Department of Statistics and Data Science, Dietrich College)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; core includes 36-707 Statistical Methods, 36-750 Statistical Computing, 36-757/36-795 Advanced Data Analysis; Data Analysis Exam at end of Spring after 36-707",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM EST). Application fee $90. Fall admission only.",
        "lang": "TOEFL iBT minimum 84 (with sub-score minimums: speaking 18, reading 22, listening 22, writing 22); IELTS minimum 7.5; Duolingo minimum 125. TOEFL code 2074 / 59.",
        "test": {"cls": "GRE OPTIONAL for the Statistics PhD program (not required since Fall 2022; may still submit). GRE REQUIRED for joint programs (Statistics/Machine Learning joint degree). GRE code 2074 / 0705. No minimum GPA; foundational courses in probability, statistics, calculus, and linear algebra are essential."},
        "tui": "Fully funded via fellowship/RA/TA. Interdisciplinary research areas: neuroscience, networks, finance, genetics, sports analytics, public policy, high-dimensional inference, and statistics/machine learning intersection. 96% of Statistics graduates report full-time positions or graduate school placement.",
        "url": "details/cmu-stat-phd.html",
    },
    {
        "id": "berkeley-stat-phd",
        "s": "berkeley",
        "n": "统计学博士",
        "en": "PhD in Statistics (Department of Statistics, UC Berkeley)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years; standard PhD provides broad background in probability theory and applied/theoretical statistics; three designated emphasis tracks available",
        "ddl": "Fall 2027: application opens September 24, 2026; deadline December 1, 2026. No spring admissions. Applications received between 150-200 per year.",
        "lang": "TOEFL iBT minimum 90. UC Berkeley does not accept Duolingo, TOEFL ITP, MyBest scores, IELTS Indicator, or IELTS One Test Retake. Institution code 4833.",
        "test": {"cls": "GRE GENERAL TEST NO LONGER REQUIRED AND WILL NOT BE ACCEPTED. GRE Math Subject Test not required but may optionally be submitted with 'Publications and Presentations'. Minimum GPA 3.0 on 4.0 scale. Descriptive list of upper division/graduate statistics and math coursework required as PDF upload. Prerequisites: linear algebra, calculus, upper division probability and statistics, familiarity with high-level programming languages."},
        "tui": "Fully funded via fellowship/RA/TA. Three designated emphasis (DE) tracks: Computational and Data Science and Engineering (CDSE), Computational and Genomic Biology, and Computational Precision Health. Admitted PhD applicants average GRE (historical) percentiles: Verbal 83%, Quantitative 94%, Analytical Writing 60% (distribution, not threshold).",
        "url": "details/berkeley-stat-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 = {
    "uchicago-booth-fin-phd": {
        "school": "University of Chicago Booth School of Business",
        "en": "PhD in Finance (Stevens Doctoral Program)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; approximately 20-25 students enter the Stevens Program each year",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM PST). Applications open early September. Decisions on or before April 15.",
        "lang": "TOEFL iBT minimum 5 overall and 5 in each subsection (for tests taken on or after January 21, 2026); IELTS minimum 7.0 overall with 7.0 in each subsection. TOEFL code 1819.",
        "test_cls": "GRE/GMAT REQUIRED of all applicants (no exceptions, even with prior graduate degrees). Finance: GRE strongly preferred, GMAT acceptable. No minimum cutoff; average GRE Quant for incoming students is 168. GRE code 1501; GMAT code H9X-9F-05. Recommended to take test by early October. Joint Program in Financial Economics (with UChicago Economics) requires GRE.",
        "tui": "Fully funded: tuition grant, stipend, student health insurance, computer or computer subsidy, and access to research and travel funding. 2026-27 admitted class profile: average GPA 3.91, average GRE Quant 168, average TOEFL 109, average age 24, 18 countries represented, 52% entering with an advanced degree.",
        "overview": "The Chicago Booth Stevens Doctoral Program is a highly competitive business PhD program. About 20-25 outstanding students enter each year. The Finance PhD prepares students for academic careers in finance. The Joint Program in Financial Economics is offered in conjunction with the UChicago Department of Economics.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE/GMAT required (Finance: GRE strongly preferred, GMAT acceptable)</li><li>TOEFL iBT 5 overall/each section (post-Jan 2026) or IELTS 7.0</li><li>Statement of purpose, CV, transcripts</li><li>3+ letters of recommendation</li><li>Application fee (waivers available)</li></ul>",
        "research": "<ul><li>Asset pricing and portfolio theory</li><li>Corporate finance</li><li>Financial econometrics</li><li>Market microstructure</li><li>Behavioral finance</li><li>International finance</li><li>Fintech and machine learning in finance</li><li>Real estate and urban economics</li></ul>",
        "source": '<a href="https://www.chicagobooth.edu/phd/faq" target="_blank">Chicago Booth PhD FAQ</a> | <a href="https://www.chicagobooth.edu/phd/admissions/how-to-apply" target="_blank">How to Apply</a> | <a href="https://www.chicagobooth.edu/phd/admissions" target="_blank">PhD Admissions</a>',
    },
    "upenn-wharton-fin-phd": {
        "school": "The Wharton School, University of Pennsylvania",
        "en": "PhD in Finance",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; coursework + preliminary written/oral exam + dissertation proposal and defense; many programs require a preliminary research paper",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM EST). Fall admission only. Decisions on or before April 15.",
        "lang": "TOEFL or IELTS required for non-native English speakers. High level of proficiency expected.",
        "test_cls": "GRE or GMAT REQUIRED (Finance: GRE or GMAT accepted; no waivers). No minimum score, but accepted applicants typically fall within the top 10 percent. Average GRE for fall 2026 entrants: Verbal 160 (80th percentile), Quantitative 169 (87th), Writing 4.2 (68th). Average GMAT: V 90th, Q 97th, Total 735 (100th). GRE code 2954-5199; GMAT code G56-97-12. Tests must be taken by December 15.",
        "tui": "All admitted students receive a FULL FELLOWSHIP including stipend, tuition coverage, and health insurance. Wharton Doctoral Programs admits for full-time study only beginning in the fall semester.",
        "overview": "The Wharton Finance PhD is one of the most prestigious finance doctoral programs in the world. The program requires coursework, a preliminary examination, a dissertation proposal, and an oral defense. Many programs also require a preliminary research paper.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL or IELTS (non-native English speakers)</li><li>Statement of purpose, CV, transcripts</li><li>3+ letters of recommendation</li><li>Fall admission only; full-time study only</li></ul>",
        "research": "<ul><li>Asset pricing</li><li>Corporate finance</li><li>Financial econometrics</li><li>Macroeconomics and finance</li><li>Market microstructure</li><li>Behavioral finance</li><li>International finance</li><li>Real estate finance</li></ul>",
        "source": '<a href="https://doctoral.wharton.upenn.edu/application-requirements/" target="_blank">Wharton Doctoral Application Requirements</a> | <a href="https://doctoral.wharton.upenn.edu/admissions/" target="_blank">Admissions</a> | <a href="https://doctoral.wharton.upenn.edu/faq/" target="_blank">FAQ</a>',
    },
    "upenn-wharton-stats-phd": {
        "school": "The Wharton School, University of Pennsylvania",
        "en": "PhD in Statistics and Data Science",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; coursework + preliminary written/oral exam + dissertation proposal and defense",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM EST). Fall admission only. Decisions on or before April 15.",
        "lang": "TOEFL or IELTS required for non-native English speakers. High level of proficiency expected.",
        "test_cls": "GRE ONLY (Statistics and Data Science program accepts GRE only; GMAT not accepted). No minimum score, but accepted applicants typically fall within the top 10 percent. Average GRE for fall 2026 entrants: Verbal 160 (80th), Quantitative 169 (87th), Writing 4.2 (68th). GRE code 2954-5199. Tests must be taken by December 15.",
        "tui": "All admitted students receive a FULL FELLOWSHIP including stipend, tuition coverage, and health insurance. Wharton Doctoral Programs admits for full-time study only beginning in the fall semester.",
        "overview": "The Wharton Statistics and Data Science PhD is offered through the Wharton School's graduate group. It prepares students for academic and research careers in statistics, data science, and business analytics.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>GRE only (GMAT not accepted for this program)</li><li>TOEFL or IELTS (non-native English speakers)</li><li>Statement of purpose, CV, transcripts</li><li>3+ letters of recommendation</li><li>Fall admission only; full-time study only</li></ul>",
        "research": "<ul><li>Statistical theory and inference</li><li>Machine learning and statistical learning</li><li>High-dimensional data analysis</li><li>Bayesian statistics</li><li>Computational statistics</li><li>Applications to finance, marketing, and healthcare</li><li>Causal inference</li><li>Data science methodology</li></ul>",
        "source": '<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 and Dates</a>',
    },
    "cmu-stat-phd": {
        "school": "Carnegie Mellon University",
        "en": "PhD in Statistics (Department of Statistics and Data Science, Dietrich College)",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; core includes 36-707 Statistical Methods, 36-750 Statistical Computing, 36-757/36-795 Advanced Data Analysis; Data Analysis Exam at end of Spring after 36-707",
        "ddl": "Fall 2027: December 1, 2026 (11:59 PM EST). Application fee $90. Fall admission only.",
        "lang": "TOEFL iBT minimum 84 (with sub-score minimums: speaking 18, reading 22, listening 22, writing 22); IELTS minimum 7.5; Duolingo minimum 125. TOEFL code 2074 / 59.",
        "test_cls": "GRE OPTIONAL for the Statistics PhD program (not required since Fall 2022; may still submit). GRE REQUIRED for joint programs (Statistics/Machine Learning joint degree). GRE code 2074 / 0705. No minimum GPA; foundational courses in probability, statistics, calculus, and linear algebra are essential.",
        "tui": "Fully funded via fellowship/RA/TA. Interdisciplinary research areas: neuroscience, networks, finance, genetics, sports analytics, public policy, high-dimensional inference, and statistics/machine learning intersection. 96% of Statistics graduates report full-time positions or graduate school placement.",
        "overview": "CMU's Department of Statistics and Data Science is world-renowned for its contributions to statistical theory and practice. The PhD program attracts exceptional students from around the world. Students may apply simultaneously to multiple programs within the department, including joint programs with Machine Learning.",
        "requirements": "<ul><li>Bachelor's degree in mathematics, engineering, sciences, economics, psychology, or related quantitative field</li><li>Foundational courses: probability, statistics, calculus, linear algebra</li><li>Statement of Purpose (2 pages maximum)</li><li>3 letters of recommendation</li><li>GRE optional (required for joint programs)</li><li>TOEFL iBT 84 / IELTS 7.5 / Duolingo 125</li><li>Application fee $90</li></ul>",
        "research": "<ul><li>Statistical theory and high-dimensional inference</li><li>Machine learning and statistical learning</li><li>Computational statistics and statistical computing</li><li>Interdisciplinary applied research: neuroscience, networks, finance, genetics, sports, public policy</li><li>Causal inference</li><li>Bayesian statistics</li><li>Statistics and machine learning intersection</li></ul>",
        "source": '<a href="https://www.cmu.edu/dietrich/statistics-datascience/academics/phd/application-process.html" target="_blank">CMU Stats PhD Application Process</a> | <a href="https://www.cmu.edu/dietrich/statistics-datascience/academics/phd/how-to-apply.html" target="_blank">How to Apply</a> | <a href="https://www.cmu.edu/dietrich/statistics-datascience/academics/phd/core/index.html" target="_blank">Core Requirements</a>',
    },
    "berkeley-stat-phd": {
        "school": "UC Berkeley Department of Statistics",
        "en": "PhD in Statistics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years; standard PhD provides broad background in probability theory and applied/theoretical statistics; three designated emphasis tracks available",
        "ddl": "Fall 2027: application opens September 24, 2026; deadline December 1, 2026. No spring admissions. Applications received between 150-200 per year.",
        "lang": "TOEFL iBT minimum 90. UC Berkeley does not accept Duolingo, TOEFL ITP, MyBest scores, IELTS Indicator, or IELTS One Test Retake. Institution code 4833.",
        "test_cls": "GRE GENERAL TEST NO LONGER REQUIRED AND WILL NOT BE ACCEPTED. GRE Math Subject Test not required but may optionally be submitted with 'Publications and Presentations'. Minimum GPA 3.0 on 4.0 scale. Descriptive list of upper division/graduate statistics and math coursework required as PDF upload. Prerequisites: linear algebra, calculus, upper division probability and statistics, familiarity with high-level programming languages.",
        "tui": "Fully funded via fellowship/RA/TA. Three designated emphasis (DE) tracks: Computational and Data Science and Engineering (CDSE), Computational and Genomic Biology, and Computational Precision Health. Admitted PhD applicants average GRE (historical) percentiles: Verbal 83%, Quantitative 94%, Analytical Writing 60% (distribution, not threshold).",
        "overview": "The UC Berkeley Statistics PhD is a rigorous program that welcomes students with interdisciplinary interests and different levels of preparation. The standard PhD provides a broad background in probability theory and applied/theoretical statistics. Three designated emphasis tracks allow formal interdisciplinary work.",
        "requirements": "<ul><li>Bachelor's degree from an accredited institution</li><li>Minimum GPA 3.0 on 4.0 scale</li><li>Prerequisites: linear algebra, calculus, upper division probability and statistics, familiarity with high-level programming languages</li><li>3 letters of recommendation</li><li>Descriptive list of upper division/graduate statistics and math coursework (PDF)</li><li>TOEFL iBT 90 minimum</li><li>GRE not accepted (as of recent policy)</li></ul>",
        "research": "<ul><li>Probability theory and stochastic processes</li><li>Statistical theory and inference</li><li>Machine learning and statistical learning</li><li>High-dimensional statistics</li><li>Computational statistics</li><li>Genomic and computational biology (DE track)</li><li>Computational precision health (DE track)</li><li>Data science and engineering (DE track)</li></ul>",
        "source": '<a href="https://statistics.berkeley.edu/academics/phd/requirements" target="_blank">Berkeley Stats PhD Requirements</a> | <a href="https://statistics.berkeley.edu/academics/faq" target="_blank">Graduate Admissions FAQ</a> | <a href="https://guide.berkeley.edu/graduate/degree-programs/statistics/statistics.pdf" target="_blank">Berkeley Guide: Statistics</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)}")
