# -*- coding: utf-8 -*-
"""r361 回填：8 条 Waterloo 的 ddl / tui（块内唯一性断言 + 备份）"""
import io, re, shutil, os

HTML = 'index_main.html'
TU = 'https://uwaterloo.ca/finance/masters-and-phd-program-tuition-fall-2026-international-0'

RESEARCH_TUI = ('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_TUI = ('2026-27 秋季国际生费率（Finance 费率表）：MEng / MMSc $17,400.00/学期、杂费 $1,014.11/学期（含 HST）；'
            '兼读 $8,700.00 + $693.99；Co-op Fee $836.00；课程型项目通常自费，部分项目设按成绩评定的入学奖；'
            '按学期计费、费率每年由 Board of Governors 批准；项目打包总额官网未公布，不估算')
MQF_TUI = ('2026-27 秋季国际生费率（Finance 费率表）：MQF $9,144.00/学期、杂费 $1,014.11/学期（含 HST）；'
           '兼读 $4,572.00 + $693.99；按学期计费、费率每年由 Board of Governors 批准；'
           '官网未公布打包总额与固定资助包金额，不估算')

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

FIELDS = {
 'uw-mqf': {'ddl': 'Fall（次年 9 月）1 月 6 日（表原文未标年份；2027 申请季对应 2027-01-06）', 'tui': MQF_TUI},
 'uw-econ-ma': {'ddl': 'Fall（次年 9 月）2 月 1 日（表原文未标年份；2027 申请季对应 2027-02-01）', 'tui': RESEARCH_TUI},
 'uw-mmsc': {'ddl': 'Fall（次年 9 月）2 月 1 日（表原文未标年份；2027 申请季对应 2027-02-01）', 'tui': MENG_TUI},
 'uw-mse-masc': {'ddl': 'Fall（次年 9 月）2 月 1 日（表原文未标年份；2027 申请季对应 2027-02-01）', 'tui': RESEARCH_TUI},
 'uw-sde-masc': {'ddl': THREE, 'tui': RESEARCH_TUI},
 'uw-meng-ece': {'ddl': THREE, 'tui': MENG_TUI},
 'uw-meng-mme': {'ddl': THREE, 'tui': MENG_TUI},
 'uw-bme-masc': {'ddl': THREE, 'tui': RESEARCH_TUI},
}

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

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
    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')))
