# -*- coding: utf-8 -*-
"""Round 228: batch add 5 Information Systems / Econometrics / Political Economics PhD
- cmu-tepper-bt-phd (CMU Tepper PhD Business Technologies)
- mit-sloan-it-phd (MIT Sloan PhD Information Technology, IT group)
- uchicago-booth-econ-stat-phd (Chicago Booth PhD Econometrics & Statistics)
- nyu-stern-is-phd (NYU Stern PhD Information Systems)
- stanford-gsb-poli-econ-phd (Stanford GSB PhD Political Economics)
Key finding: MIT Sloan IT group is GRE-ONLY (no GMAT); Stanford GSB Political Economics is GRE-only;
CMU Tepper BT, Chicago Booth E&S, NYU Stern IS accept GRE or GMAT.
Deadlines: Dec 1 (Stanford GSB, MIT Sloan) vs Dec 15 (CMU Tepper, Booth, NYU Stern).
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": "cmu-tepper-bt-phd",
        "s": "cmu",
        "n": "商业技术博士",
        "en": "PhD in Business Technologies (Tepper School of Business, Carnegie Mellon University)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years full-time; small cohort; interdisciplinary with CMU School of Computer Science; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Decisions by April 15. Fall entry only. Fee $90.",
        "lang": "TOEFL or IELTS required for non-native English speakers (including degrees from English-speaking countries). Duolingo also accepted. ETS code 2074.",
        "test": {"cls": "GRE or GMAT required (no waivers for any reason). ETS code 2074 (do NOT use 4883); GMAT code 69H-XH-19. For Economics area, faculty prefer GRE; Business Technologies accepts both. No minimum score. Acceptance rate ~3-5%."},
        "tui": "Full funding package for all admitted PhD students (tuition + stipend + health insurance). Contact Tepper PhD office for current stipend details.",
        "url": "details/cmu-tepper-bt-phd.html",
    },
    {
        "id": "mit-sloan-it-phd",
        "s": "mit",
        "n": "信息技术博士",
        "en": "PhD in Information Technology (MIT Sloan School of Management, IT group)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years full-time; average completion 6 years; ~19 students per year across all Sloan PhD areas; fall-only admission; no distance/part-time",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm ET). Fall entry only. Fee $95. No rolling admissions.",
        "lang": "TOEFL iBT minimum 90 (577 PBT); IELTS minimum 7.0. ETS code 3510. No waivers.",
        "test": {"cls": "GRE REQUIRED for IT group (per MIT Sloan: applicants to Institute for Work & Employment Research and Information Technology groups are required to take the GRE; GMAT NOT accepted). ETS code 3510. Note: other Sloan PhD groups accept GMAT (code X5X-QS-21), but IT group does not. No minimum score; at-home testing allowed. No test waivers."},
        "tui": "5-year guaranteed funding: tuition + medical insurance + fellowship stipend and/or TA/RA salary + new laptop computer + $4,500 conference travel/research budget over 5 years.",
        "url": "details/mit-sloan-it-phd.html",
    },
    {
        "id": "uchicago-booth-econ-stat-phd",
        "s": "uchicago",
        "n": "计量经济学与统计学博士",
        "en": "PhD in Econometrics & Statistics (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 Econometrics & Statistics; no area-specific GRE-only restriction). 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 -- 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-econ-stat-phd.html",
    },
    {
        "id": "nyu-stern-is-phd",
        "s": "nyu",
        "n": "信息系统博士",
        "en": "PhD in Information Systems (Stern School of Business, New York University)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; 36-54 credits (54 credits for bachelor's-only entry; at least 33 credits must be taken at NYU); fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59pm ET). Decisions late February through mid-April. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers; scores must be within last 2 years.",
        "test": {"cls": "GRE preferred, but GRE or GMAT accepted (per NYU Stern field table: Information Systems = GRE preferred, accepts both). ETS code 2582; GMAT code 5TF-HW-82. No minimum score; holistic review. No waivers. Prerequisites: calculus, linear algebra, basic probability and statistics, economics. No GRE subject tests accepted."},
        "tui": "Full funding package offered to admitted PhD students (tuition + stipend + health insurance). Contact NYU Stern PhD office for current stipend details.",
        "url": "details/nyu-stern-is-phd.html",
    },
    {
        "id": "stanford-gsb-poli-econ-phd",
        "s": "stanford",
        "n": "政治经济学博士",
        "en": "PhD in Political Economics (Stanford Graduate School of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years full-time; small cohort; interdisciplinary with Stanford Economics and Political Science departments; students begin research in Year 1; summer research papers after Years 1 and 2; 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 ONLY (per Stanford GSB field table: Political Economics = GRE only; GMAT NOT accepted, same as Organizational Behavior). ETS code 4704. All GRE scores from Dec 1, 2021-Dec 1, 2026 must be reported (no superscore). No minimum score. Note: other GSB fields (Finance, EAP, OIT, Marketing, Accounting) accept GMAT; Political Economics and OB do not."},
        "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-poli-econ-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 business school information systems / econometrics / political economics. 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 = {
    "cmu-tepper-bt-phd": {
        "school": "Carnegie Mellon University Tepper School of Business",
        "en": "PhD in Business Technologies",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5 years full-time; small cohort; interdisciplinary with CMU School of Computer Science",
        "ddl": "Fall 2027: December 15, 2026. Decisions by April 15. Fall only. Fee $90.",
        "lang": "TOEFL/IELTS/Duolingo required for non-native English speakers (including English-speaking-country degrees). ETS 2074.",
        "test_cls": "GRE or GMAT required (no waivers). ETS 2074; GMAT 69H-XH-19. Economics area prefers GRE. No minimum score. Acceptance rate ~3-5%.",
        "tui": "Full funding for all admitted PhD students (tuition + stipend + health insurance).",
        "overview": "CMU Tepper PhD in Business Technologies (BT) trains scholars who apply economics, machine learning, and quantitative methods to the study of emerging technologies. Research spans AI/ML, blockchain/cryptocurrencies, digital platforms, and the future of work. The BT program is small by design, providing close faculty interaction. Students take relevant technology courses from the CMU School of Computer Science. Graduates have placed as assistant professors at Harvard Business School, NYU Stern, Michigan Ross, Heinz College, MIT Sloan, Washington University Olin, UT Austin McCombs, UW Foster, and USC Marshall.",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative/economics preparation</li><li>GRE or GMAT required (no waivers)</li><li>TOEFL/IELTS/Duolingo (non-native English)</li><li>Statement of purpose, transcripts, CV</li><li>3 letters of recommendation (max 5)</li><li>$90 application fee</li><li>December 15, 2026 deadline</li><li>Fall entry only; full-time study</li><li>No master's degree required</li><li>Note: Tepper BT is distinct from Heinz College PhD in Information Systems Management</li></ul>",
        "research": "<ul><li>AI/ML and the economics of artificial intelligence</li><li>Blockchain and cryptocurrencies</li><li>Digital platforms and two-sided markets</li><li>Future of work and labor economics</li><li>Data science and business analytics</li><li>Information systems and technology adoption</li><li>Interdisciplinary work with CMU School of Computer Science</li><li>Marketing and economics of technology</li></ul>",
        "source": '<a href="https://www.cmu.edu/tepper/programs/phd/program/business-technologies/" target="_blank">CMU Tepper PhD Business Technologies</a> | <a href="https://www.cmu.edu/tepper/programs/phd/admissions/" target="_blank">PhD Admissions</a> | <a href="https://www.cmu.edu/tepper/programs/phd/admissions/faqs.html" target="_blank">PhD FAQ (acceptance rate)</a>',
    },
    "mit-sloan-it-phd": {
        "school": "MIT Sloan School of Management",
        "en": "PhD in Information Technology",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5-6 years full-time; average completion 6 years; ~19 students per year across all Sloan PhD areas",
        "ddl": "Fall 2027: December 1, 2026 (11:59pm ET). Fall only. Fee $95.",
        "lang": "TOEFL iBT 90 (577 PBT); IELTS 7.0. ETS 3510. No waivers.",
        "test_cls": "GRE REQUIRED for IT group (GMAT NOT accepted for IT). ETS 3510. Note: other Sloan PhD groups accept GMAT (X5X-QS-21), but IT and IWER groups do not. No minimum score; at-home testing allowed.",
        "tui": "5-year guaranteed funding: tuition + medical insurance + stipend and/or TA/RA + new laptop + $4,500 conference travel/research budget.",
        "overview": "MIT Sloan PhD in Information Technology (IT) is one of the academic groups within the MIT Sloan PhD Program. The IT group trains scholars who apply economics, information systems, and technology management to research on digital platforms, data, and organizations. The IT group is distinct from the Institute for Work & Employment Research (IWER); both groups require GRE only. MIT Sloan PhD admits about 19 students per year across all academic groups (Accounting, Economic Sociology, Finance, Information Technologies, IWER, Marketing, Organization Studies, System Dynamics, TIESM).",
        "requirements": "<ul><li>Bachelor's degree; strong quantitative background</li><li>GRE required (GMAT NOT accepted for IT group)</li><li>TOEFL 90 / IELTS 7.0 (international)</li><li>Statement of purpose, transcripts, CV</li><li>3 letters of recommendation</li><li>$95 application fee</li><li>December 1, 2026 11:59pm ET deadline</li><li>Fall entry only; no distance/part-time</li><li>Interviews only for short-listed candidates</li><li>Writing sample encouraged for research statement</li></ul>",
        "research": "<ul><li>Digital platforms and two-sided markets</li><li>Economics of information systems and technology</li><li>Data-driven decision making and business analytics</li><li>Information security and privacy</li><li>Technology and innovation management</li><li>AI and organizations</li><li>Network economics and social media</li><li>Cross-disciplinary work with MIT EECS and Sloan IT research centers</li></ul>",
        "source": '<a href="https://mitsloan.mit.edu/programs/phd/application-information" target="_blank">MIT Sloan PhD Application Information</a> | <a href="https://oge.mit.edu/programs/mit-sloan-phd-program/" target="_blank">MIT OGE Sloan PhD Profile</a> | <a href="https://mitsloan.mit.edu/programs/phd/resources-and-faqs" target="_blank">Resources & FAQs (funding)</a>',
    },
    "uchicago-booth-econ-stat-phd": {
        "school": "Chicago Booth School of Business",
        "en": "PhD in Econometrics & Statistics (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 Econometrics & Statistics; no area-specific GRE-only restriction). 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 Econometrics & Statistics is one of the dissertation areas within the Stevens Doctoral Program. It trains scholars in theoretical and applied econometrics, statistical methods, and quantitative modeling for business research. The area is distinct from Booth Economics (which is GRE-only) and from MSOM. The Stevens Program admits about 20-25 students across all dissertation areas each year. Econometrics & Statistics conducts virtual interviews for shortlisted candidates.",
        "requirements": "<ul><li>Bachelor's degree; strong mathematics/economics/statistics 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>Theoretical and applied econometrics</li><li>Bayesian econometrics and statistical modeling</li><li>High-dimensional data and machine learning</li><li>Time series and financial econometrics</li><li>Identification and causal inference</li><li>Bayesian statistics and decision theory</li><li>Computational statistics</li><li>Cross-disciplinary work with University of Chicago Department of Statistics</li></ul>",
        "source": '<a href="https://www.chicagobooth.edu/phd/admissions/how-to-apply" target="_blank">Chicago Booth PhD How to Apply</a> | <a href="https://www.chicagobooth.edu/phd/faq" target="_blank">PhD FAQ (test requirements by area)</a> | <a href="https://www.chicagobooth.edu/phd/admissions" target="_blank">Admissions (2026-27 class profile)</a>',
    },
    "nyu-stern-is-phd": {
        "school": "New York University Stern School of Business",
        "en": "PhD in Information Systems",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "4-5 years full-time; 36-54 credits (54 credits for bachelor's-only entry; at least 33 credits at NYU); fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59pm ET). Decisions late February through mid-April. Fall only.",
        "lang": "TOEFL or IELTS required for non-native English speakers; scores within last 2 years.",
        "test_cls": "GRE preferred, but GRE or GMAT accepted (per NYU Stern field table: Information Systems = GRE preferred, accepts both). ETS 2582; GMAT 5TF-HW-82. No minimum score; holistic. No waivers. Prerequisites: calculus, linear algebra, basic probability and statistics, economics. No GRE subject tests accepted.",
        "tui": "Full funding package offered to admitted PhD students (tuition + stipend + health insurance).",
        "overview": "NYU Stern PhD in Information Systems (IS) is a multidisciplinary field that grew in importance as information technology transformed the scale of data, the nature of products, the organization of work, and the way people interact. The Stern IS department has played an active leadership role in defining data science and business analytics, with cross-disciplinary scholarship in computer science, economics, machine learning, marketing, management science, and urban science. PhD students work with IS faculty who maintain close research ties with the digital, banking, advertising, and media industries, giving access to unique big-data research opportunities.",
        "requirements": "<ul><li>Bachelor's degree; prerequisites in calculus, linear algebra, basic probability and statistics, economics</li><li>GRE preferred (GMAT also accepted)</li><li>TOEFL or IELTS (non-native English, within 2 years)</li><li>Statement of purpose, optional essay, educational history, resume/CV</li><li>Letters of recommendation</li><li>Application fee</li><li>December 15, 2026 11:59pm ET deadline</li><li>Fall entry only</li><li>Comprehensive examination and dissertation defense required</li></ul>",
        "research": "<ul><li>Data science and business analytics</li><li>Economics of information systems and digital platforms</li><li>Machine learning and AI in business</li><li>Digital media and advertising technology</li><li>Fintech and banking technology</li><li>Urban science and smart cities</li><li>Information security and privacy</li><li>Cross-disciplinary work with NYU Courant, CUSP, and Tandon</li></ul>",
        "source": '<a href="http://www.stern.nyu.edu/programs-admissions/phd/admissions/how-to-apply" target="_blank">NYU Stern PhD How to Apply</a> | <a href="http://www.stern.nyu.edu/programs-admissions/phd/academics/fields-study/specialization-in-information-systems" target="_blank">Information Systems Specialization</a> | <a href="https://nyu-public.courseleaf.com/graduate/business/programs/information-systems-phd/" target="_blank">NYU Bulletin IS PhD</a>',
    },
    "stanford-gsb-poli-econ-phd": {
        "school": "Stanford Graduate School of Business",
        "en": "PhD in Political Economics",
        "deg": "Doctor of Philosophy (PhD)",
        "stem_label": "Pending department confirmation",
        "dur": "5-6 years full-time; small cohort; interdisciplinary with Stanford Economics and Political Science; students begin research in Year 1; summer research papers after Years 1 and 2",
        "ddl": "Fall 2027: December 1, 2026 (5:00pm PT). Decision by mid-February. Fall only. Fee $125.",
        "lang": "TOEFL or IELTS required per Stanford graduate admissions.",
        "test_cls": "GRE ONLY (per Stanford GSB field table: Political Economics = GRE only; GMAT NOT accepted, same as Organizational Behavior). ETS 4704. All GRE scores from Dec 1, 2021-Dec 1, 2026 must be reported (no superscore). No minimum score. Note: other GSB fields accept GMAT; Political Economics and OB do not.",
        "tui": "Full fellowship: tuition + stipend + health fee coverage. 2026-27 stipend $59,500. Knight-Hennessy Scholars available.",
        "overview": "Stanford GSB PhD in Political Economics is an interdisciplinary field focusing on the collective and political activity of individuals and organizations. The program prepares students for research and teaching positions through rigorous training in theoretical and empirical techniques. The intellectual foundation is positive political economy, including formal models of rational choice, collective action, political institutions, political competition, and behavioral political economy. The program is embedded in the larger community of political economics scholars at Stanford, combining GSB resources with cross-registration in the Economics and Political Science departments. Students begin their own research in Year 1 and write research papers during the summers after Years 1 and 2.",
        "requirements": "<ul><li>Bachelor's degree; strong analytical preparation</li><li>GRE required (GMAT NOT accepted for Political Economics)</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>Expected math preparation: one year of calculus + one course each in linear algebra, analysis, probability, optimization, statistics (to be completed or obtained in Year 1)</li><li>Successful applicants often majored in economics, mathematics, or political science as undergraduates (not a strict prerequisite)</li></ul>",
        "research": "<ul><li>Comparative political institutions</li><li>Law and economics</li><li>Political economy of development</li><li>Regulation and political economy</li><li>Rational choice and formal political theory</li><li>Behavioral political economy</li><li>Political competition and elections</li><li>Cross-disciplinary work with Stanford Economics and Political Science</li></ul>",
        "source": '<a href="https://www.gsb.stanford.edu/programs/phd/fields/political-economics" target="_blank">Stanford GSB PhD Political Economics</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://applygsb.stanford.edu/apply/" target="_blank">Application Portal (Dec 1, 5pm PT)</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)}")
