# -*- coding: utf-8 -*-
"""r363 回填：8 条 Waterloo（5 co-op + 土木 MASc + 应用数学 MMath + 化学 MSc）ddl/tui/lang/dur/test"""
import io, re, shutil, os

HTML = 'index_main.html'

RESEARCH = ('2026-27 秋季国际生费率（Finance 费率表）：研究型硕士 $7,696.00/学期、杂费 $1,014.11/学期（含 HST；'
            'Chemical Engineering $1,022.59、Mechanical and Mechatronic Engineering $1,031.06）；兼读 $3,848.00 + $693.99；'
            'Co-op Fee $836.00；研究型硕士最低资助常见一年 $12,000（Research-based funding 页），国际生另可能获 IMAE；'
            '按学期计费、费率每年由 Board of Governors 批准；项目打包总额官网未公布，不估算')
MENG = ('2026-27 秋季国际生费率（Finance 费率表）：MEng / MMSc $17,400.00/学期、杂费 $1,014.11/学期（含 HST；'
        'Chemical Engineering $1,022.59、Mechanical and Mechatronic Engineering $1,031.06）；兼读 $8,700.00 + $693.99；'
        'Co-op Fee $836.00；课程型项目通常自费，部分项目设按成绩评定的入学奖；'
        '按学期计费、费率每年由 Board of Governors 批准；项目打包总额官网未公布，不估算')
MENG_COOP = ('2026-27 秋季国际生费率（Finance 费率表）：MEng / MMSc $17,400.00/学期、杂费 $1,014.11/学期（含 HST；'
             'Chemical Engineering $1,022.59、Mechanical and Mechatronic Engineering $1,031.06）；兼读 $8,700.00 + $693.99；'
             'Co-op Fee $836.00（CEE 支持，首个学习学期首收、其后每个工作学期收取）；本项目自费、不配导师、不提供研究型资助包；'
             '按学期计费、费率每年由 Board of Governors 批准；官网未公布含 co-op 的打包总额，不估算')
MDSAI = ('2026-27 秋季国际生费率（Finance 费率表）：MDSAI 按课程计费 $6,272.00/门（非按学期统一价）、杂费 $1,014.11/学期（含 HST）、'
         'Co-op Fee $836.00（CEE 支持）；课程型专业硕士、官网未设研究型最低资助；'
         '项目需修课程门数以 Calendar 学位要求为准，官网未公布打包总额，不估算')

THREE = ('Fall（次年 9 月）2 月 1 日、Winter（次年 1 月）6 月 1 日、Spring（次年 5 月）10 月 1 日'
         '（表原文未标年份；2027 申请季对应 2027-02-01 / 2027-06-01 / 2027-10-01）')

MENG_LANG = 'TOEFL iBT 新制 4.5（写作 4.5、口语 4、阅读 4、听力 4）；IELTS Academic 6.5（写作 6.0、口语 6.0）'

FIELDS = {
 # 1 MDSAI Co-op
 'uw-mdsai-coop': {
   'ddl': 'Fall（9 月）入学，全年仅此一轮：1 月 15 日截止（表原文未标年份；2027 申请季对应 2027-01-15）',
   'tui': MDSAI,
 },
 # 2 MMSc Co-op
 'uw-mmsc-coop': {
   'ddl': 'Fall（9 月）入学，全年仅此一轮：2 月 1 日截止（表原文未标年份；2027 申请季对应 2027-02-01）',
   'tui': MENG_COOP,
 },
 # 3 MME MEng Co-op
 'uw-meng-mme-coop': {
   'ddl': THREE + '；三项均注明「完整申请含全部支持材料须在截止日前提交」',
   'tui': MENG_COOP,
 },
 # 4 ChemE MEng Co-op
 'uw-meng-cheme-coop': {
   'ddl': THREE + '；材料须在提交后 10 个工作日内且不晚于截止日上传',
   'tui': MENG_COOP,
 },
 # 5 Civil MEng Co-op
 'uw-civil-engineering-meng-coop': {
   'ddl': THREE + '；截止已过者可联系 civemeng@uwaterloo.ca 咨询备选截止',
   'tui': MENG_COOP,
   'dur': '16–20 个月（4–5 学期，含 1–2 个 co-op 工作学期）· 仅全日制 · Coursework',
   'lang': MENG_LANG,
 },
 # 6 Civil MASc
 'uw-civil-masc': {
   'ddl': THREE + '；截止已过者可联系 civegrad@uwaterloo.ca 咨询备选截止',
   'tui': RESEARCH,
 },
 # 7 Applied Mathematics MMath
 'uw-appmath-mmath': {
   'ddl': 'Fall（次年 9 月）1 月 15 日、Winter（次年 1 月）6 月 1 日、Spring（次年 5 月）10 月 1 日'
          '（表原文未标年份；2027 申请季对应 2027-01-15 / 2027-06-01 / 2027-10-01）',
   'tui': RESEARCH,
 },
 # 8 Chemistry MSc
 'uw-chem-msc': {
   'ddl': THREE,
   'tui': RESEARCH,
 },
}

TEST = {
 'uw-mdsai-coop': '',
 'uw-civil-engineering-meng-coop': '',
}

html = io.open(HTML, encoding='utf-8').read()
if not os.path.exists(HTML + '.bak_r363'):
    shutil.copy(HTML, HTML + '.bak_r363')

start = html.index('const PROGRAMS=[')
end = html.index('const CATD=[')
seg = html[start:end]

parts = seg.split('{id:"')
out = [parts[0]]
cnt = 0
for p in parts[1:]:
    pid = p.split('"', 1)[0]
    if pid in FIELDS:
        for k, v in FIELDS[pid].items():
            pat = re.compile(r'(?<![A-Za-z])' + k + r':"((?:[^"\\]|\\.)*)"')
            ms = list(pat.finditer(p))
            assert len(ms) == 1, 'field %s in %s found %d' % (k, pid, len(ms))
            p = pat.sub(lambda m: k + ':"' + v.replace('"', '\\"') + '"', p, count=1)
            cnt += 1
        if pid in TEST:
            tpat = re.compile(r'test:\{cls:"((?:[^"\\]|\\.)*)"\}')
            tms = list(tpat.finditer(p))
            assert len(tms) == 1, 'test in %s found %d' % (pid, len(tms))
            p = tpat.sub(lambda m: 'test:{cls:"' + TEST[pid] + '"}', p, count=1)
            cnt += 1
    out.append(p)

new_seg = '{id:"'.join(out)
new_html = html[:start] + new_seg + html[end:]
assert new_html != html
io.open(HTML, 'w', encoding='utf-8', newline='').write(new_html)
print('fields', cnt, 'bytes', len(new_html.encode('utf-8')))
