import re, os

path = 'index_main.html'
h = open(path, encoding='utf-8').read()

# New 5 programs
new_programs = [
    {
        'id': 'ubc-msc-cs-thesis',
        's': 'ubc',
        'n': '计算机科学理学硕士（论文型 · Vancouver）',
        'en': 'Master of Science in Computer Science (Thesis, Vancouver)',
        'deg': 'MSc',
        'lvl': 'm',
        'stem': 1,
        'dur': '2 years (full-time on-campus)',
        'ddl': 'Dec 15 (Sept admission); late applications considered until Apr 30',
        'lang': 'TOEFL iBT 90 (Reading 22, Listening 22, Speaking 21, Writing 21); IELTS 6.5 overall (6.5 each band)',
        'test': {'cls': 'GRE not required (since 2020); admission based on academic record, statement of interest, references, and fit with supervisor research'},
        'tui': 'CAD $8,043/year (2025-26, research-based MSc; funded by supervisor RA/TA where available)',
        'url': 'details/ubc-msc-cs-thesis.html',
        'official': 'https://www.cs.ubc.ca/students/grad/prospective-grads/grad-programs/full-time-masters-programs',
    },
    {
        'id': 'mcgill-msc-ece-thesis',
        's': 'mcg',
        'n': '电气与计算机工程理学硕士（论文型）',
        'en': 'Master of Science (M.Sc.) in Electrical Engineering (Thesis)',
        'deg': 'MSc',
        'lvl': 'm',
        'stem': 1,
        'dur': '1.5-2 years (full-time; minimum 3 terms residency)',
        'ddl': 'Jan 15 (Sept admission); Sep 1 (Jan admission)',
        'lang': 'TOEFL iBT 86 (Writing 20, Speaking 20); IELTS 6.5 overall (6.5 each)',
        'test': {'cls': 'GRE not required; CGPA 3.0/4.0 or GPA 3.2/4.0 in last 2 years; competitive admission requires supervisor approval'},
        'tui': 'CAD $18,000/year (international; research-funded students typically receive RA/TA)',
        'url': 'details/mcgill-msc-ece-thesis.html',
        'official': 'https://www.mcgill.ca/ece/graduate/programinfo/mastereng',
    },
    {
        'id': 'princeton-mse-mae',
        's': 'princeton',
        'n': '机械与航空航天工程工程硕士（MSE，论文型）',
        'en': 'Master of Science in Engineering (M.S.E.) in Mechanical and Aerospace Engineering',
        'deg': 'MSE',
        'lvl': 'm',
        'stem': 1,
        'dur': '2 years (full-time on-campus)',
        'ddl': 'Dec 15 (fall admission only; no spring)',
        'lang': 'TOEFL iBT 100; IELTS 7.0 overall',
        'test': {'cls': 'GRE not accepted (since 2021); admission based on transcripts, letters of recommendation, statement, research interests'},
        'tui': '~$62,000/year (MSE students typically fully funded via TA/RA covering tuition + stipend)',
        'url': 'details/princeton-mse-mae.html',
        'official': 'https://mae.princeton.edu/graduate/programs',
    },
    {
        'id': 'uva-ms-systems-engineering',
        's': 'uva',
        'n': '系统工程理学硕士（论文型 · on-campus）',
        'en': 'Master of Science in Systems Engineering (Thesis)',
        'deg': 'MS',
        'lvl': 'm',
        'stem': 1,
        'dur': '1.5-2 years (full-time on-campus)',
        'ddl': 'Dec 15 (fall admission); spring admission by petition',
        'lang': 'TOEFL iBT 90; IELTS 7.0 overall',
        'test': {'cls': 'GRE optional for 2025-2026; minimum 3.0/4.0 GPA; statement of research interests required'},
        'tui': '~$40,000/year (out-of-state; funded research assistantships available)',
        'url': 'details/uva-ms-systems-engineering.html',
        'official': 'https://records.ureg.virginia.edu/preview_program.php?catoid=50&poid=6473',
    },
    {
        'id': 'mcgill-meng-ece-nonthesis',
        's': 'mcg',
        'n': '电气与计算机工程工程硕士（课程型 · Non-Thesis）',
        'en': 'Master of Engineering (M.Eng.) in Electrical Engineering (Non-Thesis, Course-based)',
        'deg': 'MEng',
        'lvl': 'm',
        'stem': 1,
        'dur': '1 year (3 semesters, full-time on-campus; part-time available)',
        'ddl': 'Jan 15 (Sept admission); Sep 1 (Jan admission)',
        'lang': 'TOEFL iBT 86 (Writing 20, Speaking 20); IELTS 6.5 overall (6.5 each)',
        'test': {'cls': 'GRE not required; CGPA 3.0/4.0; professional course-based, no thesis; optional Applied AI concentration starting Fall 2025'},
        'tui': 'CAD $28,000/year (international, 45 credits)',
        'url': 'details/mcgill-meng-ece-nonthesis.html',
        'official': 'https://www.mcgill.ca/ece/graduate/programinfo',
    },
]

# Build detail pages
TEMPLATE = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} | {en}</title>
<style>
body{{font-family:-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;max-width:960px;margin:0 auto;padding:24px;color:#222;line-height:1.6}}
h1{{font-size:22px;border-bottom:2px solid #b31b1b;padding-bottom:8px}}
h2{{font-size:16px;color:#b31b1b;margin-top:24px}}
.meta{{color:#666;font-size:13px;margin-bottom:16px}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:12px;margin-top:12px}}
.card{{background:#f8f8f8;border-left:3px solid #b31b1b;padding:12px 14px;border-radius:4px}}
.card b{{display:block;margin-bottom:4px;color:#333}}
a{{color:#b31b1b}}
.tag{{display:inline-block;background:#b31b1b;color:#fff;font-size:11px;padding:2px 8px;border-radius:10px;margin-right:6px}}
</style>
</head>
<body>
<h1>{n}</h1>
<div class="meta">{en} · {deg} · <span class="tag">{stem_label}</span></div>
<p><a href="{official}" target="_blank">学校官方项目页 ↗</a></p>
<div class="grid">
<div class="card"><b>学制</b>{dur}</div>
<div class="card"><b>申请截止</b>{ddl}</div>
<div class="card"><b>语言要求</b>{lang}</div>
<div class="card"><b>标化要求</b>{test_cls}</div>
<div class="card"><b>学费</b>{tui}</div>
<div class="card"><b>培养方向</b>{focus}</div>
</div>
<h2>项目简介</h2>
<p>{intro}</p>
<h2>课程设置</h2>
<p style="color:#999">系站不可达，待补。</p>
<h2>申请材料清单</h2>
<p style="color:#999">系站不可达，待补。</p>
</body>
</html>
'''

infos = {
    'ubc-msc-cs-thesis': {
        'focus': 'Artificial Intelligence / Machine Learning / Systems / Graphics / HCI / Theory / Databases / Networks; 12-credit thesis option (research-focused) or Comprehensive Course Master with 3-credit essay (coursework-focused)',
        'intro': 'UBC Department of Computer Science offers a research-oriented MSc with a 12-credit thesis option (most common), a 6-credit thesis option, and a comprehensive course master option with a 3-credit major project essay. Students have two semesters to find a thesis supervisor among 80+ faculty. The program is on-campus in Vancouver, BC, Canada, and serves as preparation for PhD research or industry research careers.',
    },
    'mcgill-msc-ece-thesis': {
        'focus': 'Bioelectrical Engineering / Telecommunications & Signal Processing / Systems & Control / Integrated Circuits / Nano-Electronic Devices / Photonics / Computational Electromagnetics / Power Engineering / Intelligent Systems / Software Engineering',
        'intro': 'McGill ECE Department offers a research-oriented M.Sc. Thesis program (45 credits: 18 graduate courses + 27 thesis) with a minimum of 3 terms full-time residency. Students register for seven thesis research courses (ECSE 691-697) across three terms. The program is an ideal preparation for PhD or industrial research careers, supervised by 45+ faculty in 10 research areas.',
    },
    'princeton-mse-mae': {
        'focus': 'Thermal Sciences & Energy Conversion / Fluid Mechanics / Materials Science / Biomechanics / Control & Robotics / Dynamical Systems / Underwater Vehicles / Flight Sciences / Astronomical Instrumentation / Propulsion / Environmental Technology',
        'intro': 'Princeton MAE Department offers a 2-year M.S.E. (Master of Science in Engineering) program requiring 8 graduate courses plus an original thesis. The thesis is central and expected to address a realistic and important problem. New graduate students apply directly to the M.S.E. track; M.S.E. students may transfer to Ph.D. in good standing. The program typically covers two years with full financial support (TA/RA covering tuition + stipend).',
    },
    'uva-ms-systems-engineering': {
        'focus': 'Systems Analysis & Design / Optimization / Stochastic Modeling / Human Factors / Statistical Modeling / Decision Analysis / Risk Management / Healthcare Systems / Transportation / Energy Systems',
        'intro': 'UVA Department of Engineering Systems and Environment offers a research-oriented M.S. in Systems Engineering (30 credits beyond B.S.) built on three components: coursework, research leading to a thesis, and engagement in UVA intellectual life. The program requires SYS 6001 Introduction to Systems Analysis & Design plus 6 credits of foundation courses in optimization, stochastic modeling, human factors, or statistical modeling. Note: this is the on-campus thesis MS; the AMP (alternate-weekend) and VEO (online) versions are working-professional/remote and excluded.',
    },
    'mcgill-meng-ece-nonthesis': {
        'focus': 'Course-based professional program covering breadth across ECE plus depth in a specialty area; optional Applied Artificial Intelligence concentration starting Fall 2025',
        'intro': 'McGill ECE Department offers a professional M.Eng. Non-Thesis program (45 credits, 3 semesters) designed for students seeking course-based career advancement without thesis. The program provides a solid background across electrical and computer engineering breadth with depth in a specialty area. Part-time enrollment is available. The new Applied AI concentration launched in Fall 2025 for students targeting industry roles in machine learning and AI engineering.',
    },
}

for p in new_programs:
    stem_label = 'STEM' if p['stem'] else '非 STEM'
    info = infos[p['id']]
    html = TEMPLATE.format(
        n=p['n'], en=p['en'], deg=p['deg'], official=p['official'],
        dur=p['dur'], ddl=p['ddl'], lang=p['lang'], test_cls=p['test']['cls'],
        tui=p['tui'], stem_label=stem_label,
        focus=info['focus'], intro=info['intro'],
    )
    fp = 'details/' + p['url'].split('details/')[1]
    with open(fp, 'w', encoding='utf-8') as f:
        f.write(html)
    print(f'[OK] generated: {fp} ({len(html)} chars)')

# Append to PROGRAMS
def find_block_end(h, start_kw):
    """Find closing ]; of an array starting with start_kw."""
    idx = h.index(start_kw)
    i = idx + len(start_kw)
    depth = 0
    started = False
    while i < len(h):
        c = h[i]
        if c == '[':
            depth += 1
            started = True
        elif c == ']':
            depth -= 1
            if started and depth == 0:
                return i
        i += 1
    raise ValueError('not found')

# Build new records JS
def js_str(s):
    if isinstance(s, dict):
        return '{cls:' + json.dumps(s['cls'], ensure_ascii=False) + '}'
    return json.dumps(s, ensure_ascii=False)

import json
new_records = []
for p in new_programs:
    rec = '{' + ','.join([
        f'id:{js_str(p["id"])}',
        f's:{js_str(p["s"])}',
        f'n:{js_str(p["n"])}',
        f'en:{js_str(p["en"])}',
        f'deg:{js_str(p["deg"])}',
        f'lvl:{js_str(p["lvl"])}',
        f'stem:{p["stem"]}',
        f'dur:{js_str(p["dur"])}',
        f'ddl:{js_str(p["ddl"])}',
        f'lang:{js_str(p["lang"])}',
        f'test:{js_str(p["test"])}',
        f'tui:{js_str(p["tui"])}',
        f'url:{js_str(p["url"])}',
    ]) + '}'
    new_records.append(rec)

new_block = ','.join(new_records)

# Append before closing ];
end_idx = find_block_end(h, 'const PROGRAMS=')
# Look backward to see if char before ] is , or ]
prefix = h[:end_idx].rstrip()
if prefix.endswith(','):
    insert_text = new_block + ','
elif prefix.endswith(';') or prefix.endswith(']'):
    insert_text = ',' + new_block
else:
    insert_text = ',' + new_block
h2 = h[:end_idx] + insert_text + h[end_idx:]

# Now append to VERIFIED_DETAILS
vd_start = h2.index('const VERIFIED_DETAILS=new Set([')
vd_end = h2.index('])', vd_start)
# Get current VD content
vd_content = h2[vd_start + len('const VERIFIED_DETAILS=new Set('):vd_end+1]
# Insert new urls
new_urls = [p['url'] for p in new_programs]
new_urls_js = ','.join([json.dumps(u, ensure_ascii=False) for u in new_urls])
# vd_content ends with ] - insert before ]
vd_content_stripped = vd_content.rstrip()
if vd_content_stripped.endswith(']'):
    # if ends with ",]" then replace "], with ",new_urls]"
    if vd_content_stripped.endswith(',]'):
        new_vd = vd_content_stripped[:-2] + ',' + new_urls_js + ']'
    elif vd_content_stripped.endswith('"]'):
        new_vd = vd_content_stripped[:-1] + ',' + new_urls_js + ']'
    else:
        new_vd = vd_content_stripped[:-1] + ',' + new_urls_js + ']'
h2 = h2[:vd_start + len('const VERIFIED_DETAILS=new Set(')] + new_vd + h2[vd_end+1:]

with open(path, 'w', encoding='utf-8') as f:
    f.write(h2)

print(f'[OK] PROGRAMS appended {len(new_programs)}')
print(f'[OK] VERIFIED_DETAILS appended urls: {new_urls}')
print(f'[DONE] {path} written back ({len(h2)} chars, was {len(h)})')
