# -*- coding: utf-8 -*-
"""Round 227: batch add 5 Business School Operations/Information/Technology PhD programs
- stanford-gsb-oit-phd (Stanford GSB PhD Operations, Information & Technology)
- up-wharton-oid-phd (Wharton PhD Operations, Information & Decisions)
- uchicago-booth-msom-phd (Chicago Booth PhD Management Science & Operations Management)
- nu-kellogg-om-phd (Kellogg PhD Operations Management)
- col-dro-phd (Columbia PhD Decision, Risk, and Operations)
Key finding: Kellogg Operations Management and Columbia DRO are GRE/GMAT OPTIONAL
(no test required) -- rare among top business school PhDs.
Stanford GSB OIT / Wharton OID / Chicago Booth MSOM still require GRE or GMAT.
Deadlines: Dec 1 (Stanford GSB) vs Dec 15 (Wharton, Booth, Kellogg, Columbia).
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": "stanford-gsb-oit-phd",
        "s": "stanford",
        "n": "运营信息与技术博士",
        "en": "PhD in Operations, Information & Technology (Stanford Graduate School of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years full-time; first-year field exam covers applied probability/stochastic processes and mathematical optimization; OIT foundations courses Years 1-3; fall-only admission",
        "ddl": "Fall 2027: December 1, 2026 (5:00pm PT). Decision by mid-February. Fall entry only. Fee $125.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Stanford graduate admissions.",
        "test": {"cls": "GRE preferred, but GRE or GMAT accepted (per Stanford GSB field table: Operations, Information & Technology = GRE preferred, accepts both). ETS code 4704. GMAT code L9R-KW-27. All GRE scores from Dec 1, 2021-Dec 1, 2026 must be reported (no superscore). No minimum score."},
        "tui": "Full fellowship: tuition + stipend + health fee coverage. In 2026-27 incoming students receive a living stipend of $59,500. Research and/or course assistantships available. Knight-Hennessy Scholars available.",
        "url": "details/stanford-gsb-oit-phd.html",
    },
    {
        "id": "up-wharton-oid-phd",
        "s": "up",
        "n": "运营信息与决策博士",
        "en": "PhD in Operations, Information & Decisions (The Wharton School, University of Pennsylvania)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; coursework + preliminary written/oral exam + dissertation proposal + oral defense; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59pm EST). Decisions by April 15. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers; high proficiency expected.",
        "test": {"cls": "GRE or GMAT required (both accepted for OID). No minimum score. Fall 2026 admitted distribution: GRE V160 (80th percentile) / Q169 (87th percentile) / W4.2 (68th percentile) -- distribution, not minimum threshold. Tests must be taken no later than December 15."},
        "tui": "Full fellowship: tuition + living stipend + health insurance. All admitted Wharton doctoral students receive full funding for up to 5 years.",
        "url": "details/up-wharton-oid-phd.html",
    },
    {
        "id": "uchicago-booth-msom-phd",
        "s": "uchicago",
        "n": "管理科学与运营管理博士",
        "en": "PhD in Management Science & Operations Management (Chicago Booth School of Business, Stevens Doctoral Program)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; one of the dissertation areas within the Stevens Doctoral Program; ~20-25 students enter Stevens across all areas each year; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Virtual interviews Jan-early March; decisions by March. Fall entry only.",
        "lang": "TOEFL iBT minimum 100 (pre-Jan 2026) / 5 overall with 5 in each subsection (on/after Jan 21, 2026); IELTS minimum 7.0 overall with 7.0 sub-scores. ETS code 1819.",
        "test": {"cls": "GRE or GMAT required (both accepted for Management Science/Operations Management). ETS code 1501; GMAT code H9X-9F-05. No minimum score. 2026-27 admitted cohort distribution: average GPA 3.91, average GRE Q168, average TOEFL 109, 52% hold an advanced degree, average age 24, 18 countries represented -- distribution, not minimum threshold. Prior graduate degrees do not exempt test requirement."},
        "tui": "Full funding: tuition grant + stipend + student health insurance + computer or computer subsidy + research and travel funding. Stevens Doctoral Program funds all admitted students.",
        "url": "details/uchicago-booth-msom-phd.html",
    },
    {
        "id": "nu-kellogg-om-phd",
        "s": "nu",
        "n": "运营管理博士",
        "en": "PhD in Operations Management (Kellogg School of Management, Northwestern University)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years full-time; ~20-25 PhD students enter Kellogg across all areas each year; two years coursework + field exams + research papers + dissertation; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Decisions late February / early March. Fall entry only. Fee $95 (dual application with Economics PhD: $175).",
        "lang": "TOEFL or IELTS required for non-native English speakers per Northwestern graduate admissions. TOEFL minimum 100 (pre-Jan 2026). ETS code 1565.",
        "test": {"cls": "GRE/GMAT OPTIONAL (per Kellogg FAQ: Operations Management does not require the GRE or GMAT; test scores are optional for this program). No minimum score; holistic review. Strong quantitative preparation expected. ETS code 1565; GMAT code 6WZ-3J-54 (if submitting). Writing sample optional. Note: Kellogg Finance requires GRE preferred; MECS requires GRE-only; OM is the exception."},
        "tui": "5-year guaranteed financial aid package: tuition scholarship + stipend + health insurance + moving allowance + one-time computer subsidy ($2,000) + conference travel budget ($4,000) + additional research funding for data/software/RAs.",
        "url": "details/nu-kellogg-om-phd.html",
    },
    {
        "id": "col-dro-phd",
        "s": "col",
        "n": "决策风险与运营博士",
        "en": "PhD in Decision, Risk, and Operations (Columbia Business School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; one of the PhD divisions at Columbia Business School; highly competitive; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Application opens September 1, 2026. Fall entry only. Fee $100.",
        "lang": "TOEFL or IELTS required for non-native English speakers, unless degree earned from an English-instruction institution.",
        "test": {"cls": "GRE/GMAT OPTIONAL (per Columbia CBS application requirements: GRE/GMAT scores are OPTIONAL for DRO PhD applicants). No minimum score; test scores are only one of many factors. Two letters of recommendation required (up to four may be submitted). Optional research paper submission (up to two papers). Prerequisite: two-semester introductory calculus sequence at minimum."},
        "tui": "Full funding package offered to admitted PhD students (tuition + stipend + health insurance). Contact CBS PhD office for current stipend details.",
        "url": "details/col-dro-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 operations, information, decision sciences, and management science. 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 pending department confirmation.
</div>
</body>
</html>
"""

PAGES = {
    "stanford-gsb-oit-phd": {
        "school": "Stanford Graduate School of Business",
        "en": "PhD in Operations, Information & Technology",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5-6 years full-time; first-year field exam; OIT foundations Years 1-3",
        "ddl": "Fall 2027: December 1, 2026 (5:00pm PT). Fee $125. Fall only.",
        "lang": "TOEFL or IELTS required per Stanford graduate admissions.",
        "test_cls": "GRE preferred, but GRE or GMAT accepted. ETS 4704; GMAT L9R-KW-27. All GRE scores from Dec 1, 2021-Dec 1, 2026 must be reported (no superscore). No minimum score.",
        "tui": "Full fellowship: tuition + stipend + health fee coverage. 2026-27 stipend $59,500. Knight-Hennessy Scholars available.",
        "overview": "Stanford GSB Operations, Information & Technology (OIT) PhD trains scholars who apply mathematical models, stochastic processes, and optimization to operations, information systems, and technology. The program expects students to be familiar with calculus (advanced calculus level), linear algebra, real analysis, and probability. First-year field exam covers applied probability and stochastic processes plus mathematical optimization. OIT students take four foundational courses in Year 1 and two OIT foundations courses across Years 1-3. The GSB PhD admits a cohort of 20-25 students across all 7 fields each year.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative preparation (advanced calculus, linear algebra, real analysis, probability)</li><li>GRE preferred (GMAT also accepted)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, resume/CV, transcripts</li><li>3 letters of reference</li><li>$125 application fee</li><li>December 1, 2026 5:00pm PT deadline</li><li>Fall entry only; no minimum GPA or GRE score</li><li>Students without linear programming, constrained optimization, microeconomics, or statistics background should do pre-program reading</li></ul>",
        "research": "<ul><li>Applied probability and stochastic processes</li><li>Mathematical optimization and convex optimization</li><li>Operations management and supply chain management</li><li>Market design and auction theory</li><li>Information systems and platform economics</li><li>Technology and innovation management</li><li>Revenue management and pricing</li><li>Healthcare operations and service systems</li></ul>",
        "source": '<a href="https://gsb.stanford.edu/programs/phd/fields/operations-information-technology/requirements" target="_blank">Stanford GSB PhD OIT Requirements</a> | <a href="https://www.gsb.stanford.edu/programs/phd/admission/application-materials/gmat-gre" target="_blank">GMAT & GRE Field Table</a> | <a href="https://www.gsb.stanford.edu/programs/phd/admission" target="_blank">PhD Admission</a>',
    },
    "up-wharton-oid-phd": {
        "school": "The Wharton School, UPenn",
        "en": "PhD in Operations, Information & Decisions",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years full-time; coursework + preliminary exam + dissertation",
        "ddl": "Fall 2027: December 15, 2026 (11:59pm EST). Decisions by April 15. Fall only.",
        "lang": "TOEFL or IELTS required; high proficiency expected.",
        "test_cls": "GRE or GMAT required (both accepted). No minimum score. Fall 2026 admitted distribution: GRE V160 (80th pct) / Q169 (87th pct) / W4.2 (68th pct) -- distribution, not minimum. Tests must be taken by December 15.",
        "tui": "Full fellowship: tuition + living stipend + health insurance. All admitted Wharton doctoral students funded for up to 5 years.",
        "overview": "Wharton Operations, Information & Decisions (OID) is one of nine PhD programs at the Wharton Doctoral Programs. It trains scholars who apply stochastic modeling, optimization, game theory, and econometrics to operations, information systems, and managerial decision-making. Full-time study only, beginning in the fall semester. The program includes coursework, a preliminary written or oral examination, a dissertation proposal, and oral defense; many programs also require a preliminary research paper.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative preparation</li><li>GRE or GMAT (both accepted)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, applicant history, transcripts</li><li>Letters of recommendation</li><li>December 15, 2026 11:59pm EST deadline</li><li>Fall entry only; full-time study</li><li>Preliminary research paper typically required</li><li>No deferral of admission offer</li></ul>",
        "research": "<ul><li>Operations management and supply chain</li><li>Information systems and the economics of IT</li><li>Decision processes and behavioral operations</li><li>Stochastic models and probability</li><li>Optimization and mathematical programming</li><li>Revenue management and pricing</li><li>Healthcare operations</li><li>Market platforms and network economics</li></ul>",
        "source": '<a href="https://doctoral.wharton.upenn.edu/overview/facts-and-dates/" target="_blank">Wharton Doctoral Facts & Dates</a> | <a href="https://doctoral.wharton.upenn.edu/application-requirements/" target="_blank">Application Requirements</a> | <a href="https://doctoral.wharton.upenn.edu/faq/" target="_blank">FAQ (admitted GRE distribution)</a>',
    },
    "uchicago-booth-msom-phd": {
        "school": "Chicago Booth School of Business",
        "en": "PhD in Management Science & Operations Management (Stevens Doctoral Program)",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years full-time; one of the Stevens dissertation areas; ~20-25 students enter Stevens across all areas each year",
        "ddl": "Fall 2027: December 15, 2026. Virtual interviews Jan-early March; decisions by March. Fall only.",
        "lang": "TOEFL iBT 100 (pre-Jan 2026) / 5 overall with 5 subsections (on/after Jan 21, 2026); IELTS 7.0 overall with 7.0 sub-scores. ETS 1819.",
        "test_cls": "GRE or GMAT required (both accepted for MSOM). ETS 1501; GMAT H9X-9F-05. No minimum score. 2026-27 admitted distribution: avg GPA 3.91, avg GRE Q168, avg TOEFL 109, 52% advanced degree, avg age 24, 18 countries -- distribution, not minimum. Prior graduate degrees do not exempt.",
        "tui": "Full funding: tuition grant + stipend + health insurance + computer subsidy + research and travel funding. Stevens Program funds all admitted students.",
        "overview": "Chicago Booth PhD in Management Science and Operations Management is one of the dissertation areas within the Stevens Doctoral Program. It combines concepts, models, and data to generate research that helps managers make better operations decisions. Research spans healthcare analytics, criminal justice operations, mathematical modeling, and data-driven decision-making. The Stevens Program admits about 20-25 students across all dissertation areas each year. MSOM is one of the areas that conducts virtual interviews (January-early March).",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative preparation</li><li>GRE or GMAT required (no exemptions for prior graduate degrees)</li><li>TOEFL 100 / IELTS 7.0 (international)</li><li>Statement of purpose, transcripts, CV</li><li>Letters of recommendation</li><li>December 15, 2026 deadline</li><li>Fall entry only; full-time Stevens Doctoral Program</li><li>Virtual interviews for shortlisted candidates</li><li>Applicants may apply to only one dissertation area per cycle</li></ul>",
        "research": "<ul><li>Healthcare analytics and delivery operations</li><li>Criminal justice operations</li><li>Data-driven decision-making and managerial decision models</li><li>Stochastic modeling and optimization</li><li>Market design and platform economics</li><li>Supply chain and inventory management</li><li>Revenue management and pricing</li><li>Computational social science and behavioral operations</li></ul>",
        "source": '<a href="https://www.chicagobooth.edu/faculty/academic-areas/operations-management" target="_blank">Chicago Booth Operations Management</a> | <a href="https://www.chicagobooth.edu/phd/admissions/how-to-apply" target="_blank">How to Apply (test requirements by area)</a> | <a href="https://www.chicagobooth.edu/phd/faq" target="_blank">PhD FAQ (2026-27 class profile)</a>',
    },
    "nu-kellogg-om-phd": {
        "school": "Northwestern University Kellogg School of Management",
        "en": "PhD in Operations Management",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5 years full-time; ~20-25 students enter Kellogg across all areas each year; two years coursework + field exams + research papers + dissertation",
        "ddl": "Fall 2027: December 15, 2026. Decisions late February / early March. Fall only. Fee $95 (dual with Economics PhD: $175).",
        "lang": "TOEFL or IELTS required per Northwestern graduate admissions. TOEFL minimum 100 (pre-Jan 2026). ETS 1565.",
        "test_cls": "GRE/GMAT OPTIONAL (per Kellogg FAQ: Operations Management does not require GRE or GMAT; test scores are optional). No minimum score; holistic. ETS 1565; GMAT 6WZ-3J-54 (if submitting). Writing sample optional. Note: Kellogg Finance prefers GRE; MECS requires GRE-only; OM is the exception.",
        "tui": "5-year guaranteed aid: tuition scholarship + stipend + health insurance + moving allowance + $2,000 one-time computer subsidy + $4,000 conference travel budget + additional research funding.",
        "overview": "Kellogg PhD in Operations Management focuses on managerial decision-making of operations functions in firms through quantitative, economic modeling, and empirical analysis. Active research areas include supply-chain management, sustainability, service management, capacity and production planning, processing networks, revenue management, healthcare management, retail operations, and contracting/economic-mechanism design. Averaging about 25 PhD students across all Kellogg areas each year. Kellogg OM is the rare top business school PhD where GRE/GMAT is optional -- a stark contrast to Kellogg Finance (GRE preferred) and MECS (GRE-only).",
        "requirements": "<ul><li>Bachelor's degree before enrollment</li><li>GRE/GMAT optional (not required for Operations Management)</li><li>TOEFL or IELTS (non-native English)</li><li>Statement of purpose, transcripts, resume</li><li>Letters of recommendation</li><li>$95 application fee (dual Economics PhD: $175)</li><li>December 15, 2026 deadline</li><li>Fall entry only; no online/part-time</li><li>Strong quantitative and verbal skills expected</li><li>Writing sample optional; course form listing six rigorous math/econ courses recommended for quantitative programs</li></ul>",
        "research": "<ul><li>Supply chain management and logistics</li><li>Sustainability and green operations</li><li>Service management and service operations</li><li>Capacity planning and production control</li><li>Processing networks and queueing</li><li>Revenue management and pricing</li><li>Healthcare operations and hospital management</li><li>Retail operations and contracting / mechanism design</li></ul>",
        "source": '<a href="http://www.kellogg.northwestern.edu/doctoral/faqs/" target="_blank">Kellogg PhD FAQ (test requirements by area)</a> | <a href="http://www.kellogg.northwestern.edu/admissions/phd-admissions/phd-how-to-apply/" target="_blank">How to Apply</a> | <a href="http://www.kellogg.northwestern.edu/admissions/phd-admissions/phd-tuition-and-fin-aid/" target="_blank">Tuition & Financial Aid</a>',
    },
    "col-dro-phd": {
        "school": "Columbia Business School",
        "en": "PhD in Decision, Risk, and Operations",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years full-time; one of the PhD divisions at Columbia Business School; highly competitive; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Application opens September 1, 2026. Fall only. Fee $100.",
        "lang": "TOEFL or IELTS required unless degree earned from an English-instruction institution.",
        "test_cls": "GRE/GMAT OPTIONAL (per Columbia CBS application requirements: GRE/GMAT scores are OPTIONAL for DRO PhD applicants). No minimum score; test scores are only one of many factors. Two letters of recommendation required (up to four may be submitted). Optional research paper submission (up to two papers). Prerequisite: two-semester introductory calculus sequence at minimum.",
        "tui": "Full funding package offered to admitted PhD students (tuition + stipend + health insurance). Contact CBS PhD office for current stipend details.",
        "overview": "Columbia Business School PhD in Decision, Risk, and Operations (DRO) focuses on the mathematical and analytical foundations of decision-making, risk management, and operations. The division is interested in candidates who can use mathematics as a language -- translating verbal descriptions of phenomena into appropriate mathematical frameworks. DRO is the rare top business school PhD where GRE/GMAT is optional, and applicants may submit up to two research papers. The ideal candidate has a strong quantitative background; a master's degree is not required but many applicants hold one in management, economics, psychology, sociology, or statistics.",
        "requirements": "<ul><li>Bachelor's degree (four-year accredited program); master's not required</li><li>Two-semester introductory calculus sequence at minimum; strong math background essential</li><li>GRE/GMAT optional (not required for DRO applicants)</li><li>TOEFL or IELTS (non-native English, unless English-instruction degree)</li><li>Statement/essay, transcripts, CV</li><li>2 letters of recommendation required (up to 4 may be submitted)</li><li>Optional research paper (up to two papers, submitted via Essays section)</li><li>$100 application fee</li><li>December 15, 2026 deadline</li><li>Fall entry only; no rolling admissions</li></ul>",
        "research": "<ul><li>Decision theory and behavioral decision-making</li><li>Risk management and financial risk</li><li>Operations management and supply chain</li><li>Optimization and mathematical programming</li><li>Game theory and market design</li><li>Information and decision processes</li><li>Data-driven operations and business analytics</li><li>Modeling and quantitative methods</li></ul>",
        "source": '<a href="https://academics.business.columbia.edu/phd/dro/admissions" target="_blank">Columbia DRO PhD Admissions</a> | <a href="https://academics.business.columbia.edu/admissions/phd/application-requirements" target="_blank">Application Requirements (GRE/GMAT optional for DRO)</a> | <a href="https://academics.business.columbia.edu/admissions/phd" target="_blank">CBS PhD Admissions</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)}")
