# -*- coding: utf-8 -*-
"""Round 222: batch add 5 Marketing PhD programs (Top business schools)
- up-wharton-mkt-phd (Wharton PhD Marketing)
- stanford-gsb-mkt-phd (Stanford GSB PhD Marketing)
- uchicago-booth-mkt-phd (Chicago Booth Stevens PhD Marketing)
- nu-kellogg-mkt-phd (Northwestern Kellogg PhD Marketing)
- col-gsb-mkt-phd (Columbia Business School PhD Marketing)
Pattern: all 5 require GRE or GMAT (Marketing accepts both); deadlines cluster Dec 1 (Stanford) or Dec 15 (Wharton/Booth/Kellogg/Columbia).
All are fully funded PhD programs.
"""
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
DET = os.path.join(BASE, "details")
os.makedirs(DET, exist_ok=True)

PROGRAMS = [
    {
        "id": "up-wharton-mkt-phd",
        "s": "up",
        "n": "市场营销博士",
        "en": "PhD in Marketing (Wharton School, University of Pennsylvania)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; coursework + preliminary written/oral exam + dissertation proposal and defense; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM EST). All tests must be taken by Dec 15. Decisions by April 15. Full-time only; fall entry only.",
        "lang": "TOEFL iBT or IELTS required for non-native English speakers. High proficiency expected. Scores must be within 5 years.",
        "test": {"cls": "GRE or GMAT required for Marketing (both accepted). No minimum score; admitted average GRE V160/Q169/W4.2, GMAT Total 735 (distribution, not threshold). ETS code 2954-5199 or 2954-0000; GMAT G56-97-12. Cannot be waived. Note: Wharton Statistics & Data Science is GRE-only, but Marketing accepts both."},
        "tui": "All admitted Wharton doctoral students receive a full fellowship: tuition + living stipend + health insurance.",
        "url": "details/up-wharton-mkt-phd.html",
    },
    {
        "id": "stanford-gsb-mkt-phd",
        "s": "stanford",
        "n": "市场营销博士",
        "en": "PhD in Marketing (Stanford Graduate School of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years full-time; one of seven GSB doctoral fields (Accounting / EAP / Finance / Marketing / OIT / OB / Political Economy); incoming cohort 20-25 across all fields",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM PT). Decisions by mid-March. No deferral policy. Fall entry only.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Stanford graduate admissions.",
        "test": {"cls": "GRE required of all applicants (no GMAT for GSB PhD). ETS institutional code 4704 (no department code). For Fall 2027, accept GRE scores from Dec 1, 2021 to Dec 1, 2026. Must submit complete history of all GRE tests in range (no superscoring). Self-reported accepted pending official."},
        "tui": "Full financial fellowship: tuition + health fees + $59,500 annual living stipend (2026-27 rate). 5-6 years guaranteed funding with satisfactory academic progress. Knight-Hennessy Scholars available (up to 3 years additional leadership program + funding).",
        "url": "details/stanford-gsb-mkt-phd.html",
    },
    {
        "id": "uchicago-booth-mkt-phd",
        "s": "uchicago",
        "n": "市场营销博士",
        "en": "Stevens Doctoral Program PhD in Marketing (Chicago Booth School of Business)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; coursework and general exam in first 2 years; dissertation begins Year 3; about 20-25 students enter Stevens Program each year across all fields",
        "ddl": "Fall 2027: December 15, 2026. You may only apply to ONE dissertation area per year. Fall entry only.",
        "lang": "TOEFL iBT minimum 100 (pre-Jan 21 2026) or overall 5 with 5 in each section (post-Jan 21 2026); IELTS overall 7.0 with sub-scores 7.0 each. ETS code 1819; IELTS TRF to phd@chicagobooth.edu.",
        "test": {"cls": "GRE or GMAT required for Marketing (both accepted). No exceptions; prior graduate degrees do not exempt. Average admitted GRE Quant 168 (distribution, not threshold). GRE code 1501; GMAT H9X-9F-05. Scores valid 5 years. Take test by early October for timely receipt."},
        "tui": "PhD students receive tuition grant + stipend + student health insurance + computer/subsidy + research and travel funding. 2026-27 admitted profile: avg GPA 3.91, avg GRE Q168, avg TOEFL 109, avg age 24, 52% hold advanced degrees.",
        "url": "details/uchicago-booth-mkt-phd.html",
    },
    {
        "id": "nu-kellogg-mkt-phd",
        "s": "nu",
        "n": "市场营销博士",
        "en": "PhD in Marketing (Kellogg School of Management, Northwestern University)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years full-time; 2 tracks: Consumer Behavior (CB) OR Quantitative Marketing (Quant); about 25 PhD students enter Kellogg each year across all programs; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Application fee $95 (or $175 dual application with Economics PhD). Decisions late February/early March. No online/part-time.",
        "lang": "TOEFL or IELTS required for non-native English speakers. Northwestern Graduate School minimum TOEFL iBT 90 (pre-Jan 21 2026) or 4.5 (post-Jan 21 2026). ETS code 1565, dept 01.",
        "test": {"cls": "GRE or GMAT required for Marketing (both accepted). GRE code 1565 (Northwestern Graduate School, no dept code); GMAT 6WZ-3J-54 (Kellogg PhD). No minimum score; holistic review. For Quant track: recommended coursework in calculus, real analysis, linear algebra, optimization, probability, statistics. Writing sample optional."},
        "tui": "All PhD students receive 5-year guaranteed financial aid: stipend + full tuition scholarship + annual health insurance. Incoming students also receive moving allowance, computer subsidy, and conference travel budget.",
        "url": "details/nu-kellogg-mkt-phd.html",
    },
    {
        "id": "col-gsb-mkt-phd",
        "s": "col",
        "n": "市场营销博士",
        "en": "PhD in Marketing (Columbia Business School)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "4-5 years full-time; two subareas: Consumer Behavior and Quantitative Modeling; typically admits only about 4 students per year; fall-only admission",
        "ddl": "Fall 2027: application opens September 1, 2026; deadline December 15, 2026. Application fee $100. Fall entry only.",
        "lang": "TOEFL or IELTS required unless applicant holds a degree from an institution where English was the language of instruction.",
        "test": {"cls": "GRE or GMAT required (one of the two). No minimum score. Essay required: <1000 words describing research interests and subarea fit (CB or Quant; non-binding). 2 letters of recommendation required (up to 4 accepted). Note: DRO PhD is GRE/GMAT-optional, but Marketing requires one."},
        "tui": "Fully funded by Columbia Business School: tuition + stipend + health insurance. PhD Admitted Students Day hosted for invited candidates.",
        "url": "details/col-gsb-mkt-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>No (business school doctoral program)</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 at a top business school. 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 = {
    "up-wharton-mkt-phd": {
        "school": "Wharton School, UPenn",
        "en": "PhD in Marketing",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years full-time; preliminary exam + dissertation",
        "ddl": "Fall 2027: December 15, 2026 (11:59 PM EST). Decisions by April 15.",
        "lang": "TOEFL iBT or IELTS required. High proficiency expected.",
        "test_cls": "GRE or GMAT (both accepted for Marketing). Avg admitted GRE V160/Q169/W4.2, GMAT 735. ETS 2954-5199; GMAT G56-97-12. Cannot waive.",
        "tui": "Full fellowship: tuition + stipend + health insurance for all admitted students.",
        "overview": "Wharton's PhD in Marketing is one of nine doctoral programs at the Wharton School. It combines rigorous training in marketing theory, quantitative methods, and consumer behavior. The program typically takes 4-5 years and includes coursework, a preliminary written/oral exam, and a dissertation.",
        "requirements": "<ul><li>Bachelor's degree; master's not required</li><li>GRE or GMAT (Marketing accepts both)</li><li>TOEFL or IELTS (non-native English)</li><li>3 letters of recommendation</li><li>Statement of purpose, applicant history, transcripts</li><li>December 15, 2026 deadline</li><li>Full-time study; fall entry only</li><li>Tests must be taken by Dec 15; send official scores by then</li></ul>",
        "research": "<ul><li>Consumer behavior and decision-making</li><li>Quantitative marketing and econometrics</li><li>Pricing and promotion</li><li>Digital marketing and analytics</li><li>Consumer choice and demand estimation</li><li>Strategic marketing and competition</li><li>Marketing model building</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/faq/" target="_blank">FAQ (avg scores)</a> | <a href="https://doctoral.wharton.upenn.edu/admissions/" target="_blank">Admissions</a>',
    },
    "stanford-gsb-mkt-phd": {
        "school": "Stanford Graduate School of Business",
        "en": "PhD in Marketing",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years full-time; 20-25 students enter GSB PhD across all 7 fields each year",
        "ddl": "Fall 2027: December 1, 2026 (5:00 PM PT). Decisions by mid-March. No deferral.",
        "lang": "TOEFL or IELTS required for non-native English speakers per Stanford graduate admissions.",
        "test_cls": "GRE required of all applicants (no GMAT). ETS code 4704. Accept scores Dec 1, 2021 - Dec 1, 2026. Must submit complete history (no superscoring). Self-reported accepted.",
        "tui": "Full fellowship: tuition + health fees + $59,500 annual living stipend (2026-27). 5-6 years guaranteed funding. Knight-Hennessy Scholars available.",
        "overview": "Stanford GSB PhD in Marketing is one of seven doctoral fields (Accounting, Economic Analysis & Policy, Finance, Marketing, Operations Information & Technology, Organizational Behavior, Political Economics). The program is designed for careers in research and teaching at leading academic institutions.",
        "requirements": "<ul><li>Bachelor's degree</li><li>GRE required (no GMAT)</li><li>Statement of purpose, CV/education</li><li>Letters of recommendation</li><li>TOEFL or IELTS (non-native English)</li><li>December 1, 2026 5:00 PM PT deadline</li><li>Fall entry only; no deferral</li><li>May apply to Stanford GSB PhD and another Stanford program simultaneously</li></ul>",
        "research": "<ul><li>Consumer behavior and psychology</li><li>Quantitative marketing and structural econometrics</li><li>Marketing strategy and firm behavior</li><li>Digital marketing and platform economics</li><li>Consumer choice and demand</li><li>Neuroscience and decision-making</li><li>Pricing, advertising, and promotion</li></ul>",
        "source": '<a href="https://www.gsb.stanford.edu/programs/phd" target="_blank">Stanford GSB PhD Program</a> | <a href="https://www.gsb.stanford.edu/programs/phd/admission/application-materials/graduate-record-examination-gre" target="_blank">GRE Requirements</a> | <a href="https://www.gsb.stanford.edu/programs/phd/admission/deadline-decisions" target="_blank">Deadline & Decisions</a>',
    },
    "uchicago-booth-mkt-phd": {
        "school": "Chicago Booth",
        "en": "Stevens Doctoral Program PhD in Marketing",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years full-time; ~20-25 students enter Stevens Program each year across all fields; general exam by end of Year 2; dissertation begins Year 3",
        "ddl": "Fall 2027: December 15, 2026. Only ONE dissertation area per application year. Fall entry only.",
        "lang": "TOEFL iBT 100 (pre-Jan 21 2026) or 5 overall with 5 in each section (post-Jan 21 2026); IELTS 7.0 with sub-scores 7.0. ETS 1819; IELTS TRF to phd@chicagobooth.edu.",
        "test_cls": "GRE or GMAT required for Marketing (both accepted). No exceptions; prior graduate degrees do not exempt. Avg admitted GRE Quant 168 (distribution). GRE code 1501; GMAT H9X-9F-05. Take by early October for timely receipt.",
        "tui": "Tuition grant + stipend + student health insurance + computer/subsidy + research and travel funding. 2026-27 admitted profile: avg GPA 3.91, avg GRE Q168, avg TOEFL 109, avg age 24, 52% advanced degrees.",
        "overview": "The Chicago Booth Stevens Doctoral Program in Marketing trains scholars in consumer behavior and economics/quantitative methods. Students take courses across the University of Chicago in psychology, sociology, economics, computer science, and statistics, and may access TTIC computer science courses.",
        "requirements": "<ul><li>Bachelor's degree from accredited institution</li><li>GRE or GMAT required (no waiver)</li><li>TOEFL 100 / IELTS 7.0</li><li>Statement of purpose, essays, CV</li><li>Letters of recommendation</li><li>December 15, 2026 deadline</li><li>Only one dissertation area per year</li><li>Fall entry only</li></ul>",
        "research": "<ul><li>Consumer behavior and judgment/decision-making</li><li>Quantitative marketing and structural econometrics</li><li>Pricing, promotion, and targeting</li><li>Product design and positioning</li><li>Channel strategy and firm competition</li><li>Neuromarketing and consumer psychology</li><li>Digital and social media marketing</li></ul>",
        "source": '<a href="https://www.chicagobooth.edu/phd/admissions/how-to-apply" target="_blank">Booth PhD How to Apply</a> | <a href="https://www.chicagobooth.edu/phd/faq" target="_blank">PhD FAQ</a> | <a href="https://news.chicagobooth.edu/chicago-booth/home/phd/dissertation-areas/marketing" target="_blank">Marketing PhD</a>',
    },
    "nu-kellogg-mkt-phd": {
        "school": "Kellogg School of Management, Northwestern",
        "en": "PhD in Marketing",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years full-time; 2 tracks: Consumer Behavior (CB) OR Quantitative Marketing (Quant); ~25 PhD students enter Kellogg across all programs each year; fall-only admission",
        "ddl": "Fall 2027: December 15, 2026. Fee $95 (or $175 dual application with Economics PhD). Decisions late February/early March. No online/part-time.",
        "lang": "TOEFL or IELTS required. Northwestern Graduate School minimum TOEFL iBT 90 (pre-Jan 21 2026) or 4.5 (post-Jan 21 2026). ETS code 1565, dept 01.",
        "test_cls": "GRE or GMAT required for Marketing (both accepted). GRE code 1565; GMAT 6WZ-3J-54. No minimum; holistic review. Quant track recommends calculus, real analysis, linear algebra, optimization, probability, statistics. Writing sample optional.",
        "tui": "5-year guaranteed financial aid: stipend + full tuition scholarship + annual health insurance. Moving allowance, computer subsidy, conference travel budget included.",
        "overview": "Kellogg's Marketing PhD offers two tracks: Consumer Behavior (CB) joins social psychology with decision-making; Quantitative Marketing (Quant) uses economics, statistics, and econometrics to study consumer choice, pricing, promotion, and field experiments. About half of entering students hold a graduate degree.",
        "requirements": "<ul><li>Bachelor's degree; master's not required (about half of entering students have one)</li><li>GRE or GMAT (both accepted)</li><li>TOEFL or IELTS (non-native English)</li><li>3+ letters of recommendation</li><li>Statement of purpose, resume, transcripts</li><li>$95 application fee ($175 dual with Economics PhD)</li><li>December 15, 2026 deadline</li><li>Fall entry only; no online/part-time</li></ul>",
        "research": "<ul><li>Consumer Behavior (CB): social psychology, judgment, choice complexity, consumer identity</li><li>Quantitative Marketing (Quant): empirical/analytical techniques, consumer choice, pricing, promotion, competitive strategy, digital marketing, field experiments</li><li>Structural econometrics</li><li>Marketing model building</li><li>Big data and customer analytics</li></ul>",
        "source": '<a href="http://www.kellogg.northwestern.edu/doctoral/programs/marketing/" target="_blank">Kellogg PhD in Marketing</a> | <a href="https://kellogg.northwestern.edu/admissions/phd-admissions/phd-how-to-apply/" target="_blank">How to Apply</a> | <a href="http://www.kellogg.northwestern.edu/doctoral/faqs/" target="_blank">PhD FAQ</a>',
    },
    "col-gsb-mkt-phd": {
        "school": "Columbia Business School",
        "en": "PhD in Marketing",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "4-5 years full-time; two subareas: Consumer Behavior and Quantitative Modeling; typically admits only ~4 students per year; fall-only admission",
        "ddl": "Fall 2027: application opens September 1, 2026; deadline December 15, 2026. Fee $100. Fall entry only.",
        "lang": "TOEFL or IELTS required unless applicant holds a degree from an institution where English was the language of instruction.",
        "test_cls": "GRE or GMAT required (one of the two). No minimum score. Essay <1000 words on research interests and subarea (CB or Quant; non-binding). 2 letters required (up to 4 accepted). Note: DRO PhD is GRE/GMAT-optional, but Marketing requires one.",
        "tui": "Fully funded by Columbia Business School: tuition + stipend + health insurance. PhD Admitted Students Day hosted for invited candidates.",
        "overview": "Columbia Business School's Marketing PhD is highly selective, typically admitting only about 4 students per year. Students indicate a subarea (Consumer Behavior or Quantitative Modeling) on the application, but take a common core curriculum and are free to work on any marketing-related topics.",
        "requirements": "<ul><li>Bachelor's degree; master's not required (many applicants hold master's in management, economics, psychology, sociology, statistics)</li><li>GRE or GMAT required</li><li>TOEFL or IELTS (if applicable)</li><li>Essay <1000 words on research interests and subarea fit</li><li>2 letters of recommendation (up to 4 accepted)</li><li>Transcripts</li><li>$100 application fee</li><li>December 15, 2026 deadline</li></ul>",
        "research": "<ul><li>Consumer Behavior: psychological and social drivers of consumer decisions</li><li>Quantitative Modeling: econometric and statistical models of demand, pricing, advertising</li><li>Marketing strategy and firm behavior</li><li>Digital marketing and social media</li><li>Neuromarketing and behavioral decision research</li><li>Product and brand management</li></ul>",
        "source": '<a href="https://academics.business.columbia.edu/phd/marketing/admissions" target="_blank">CBS PhD Admissions in Marketing</a> | <a href="https://academics.business.columbia.edu/admissions/phd/application-requirements" target="_blank">Application Requirements</a> | <a href="https://academics.business.columbia.edu/admissions/phd" target="_blank">PhD Admissions Overview</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)}")
