# -*- coding: utf-8 -*-
"""讲稿 Markdown → 打印版 HTML（再由 soffice 转 A4 PDF）。

用法：python _make_print.py
输出：_print/第1章-打印版.html、第2章-打印版.html、合订.html、备课批注版.html
"""
import html as H
import os
import re

BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, '_print')
os.makedirs(OUT, exist_ok=True)

CH = {3: '第2章-软件项目启动-讲稿-教材精读增强版.md'}
TITLE = {3: '第 2 章　软件项目启动（教材精读增强版）'}
SUB = {3: '第 2 周 · 2 学时（90 分钟）｜ 教材：宋莹莹等《软件项目管理与实践》（第 3 版）｜ 已并入教材第 2 章（书页 15–32）原文细节与表格'}

CSS = """
@page { size: A4; margin: 16mm 14mm; }
body { font-family: "Microsoft YaHei","PingFang SC","Noto Sans CJK SC",sans-serif; font-size: 10.5pt; line-height: 1.65; color:#1f2937; }
h1 { font-size: 17pt; color:#1a365d; border-bottom:2px solid #1a365d; padding-bottom:6px; }
h2 { font-size: 13pt; color:#1a365d; margin-top:18px; border-left:5px solid #c49340; padding-left:8px; }
h3 { font-size: 12pt; color:#9E1F24; margin:16px 0 6px; border-bottom:1px dashed #cbd5e0; padding-bottom:3px; page-break-after:avoid; }
table { width:100%; border-collapse:collapse; margin:8px 0 12px; font-size:9.5pt; }
th,td { border:1px solid #cbd5e0; padding:5px 7px; text-align:left; vertical-align:top; }
th { background:#f2f6fa; color:#1a365d; }
blockquote { margin:6px 0; padding:8px 12px; background:#f7fbff; border-left:4px solid #2b6cb0; border-radius:0 6px 6px 0; }
blockquote p { margin:0; }
p { margin:4px 0; }
strong { color:#1a365d; }
.pageblock { page-break-inside:auto; }
.speak { background:#fffdf5; border-left:4px solid #c49340; }
.exam { background:#fff5f5; border-left:4px solid #e53e3e; }
.sz { background:#f0fff4; border-left:4px solid #2f855a; }
.q { background:#f5f7fa; border-left:4px solid #718096; }
.note { color:#a0aec0; font-size:9pt; border-bottom:1px dotted #cbd5e0; margin:2px 0 10px; }
.cover { text-align:center; padding-top:40mm; page-break-after:always; }
.cover h1 { border:0; font-size:24pt; }
.cover p { color:#4a5568; }
"""

LABELS = {'板书': 'board', '提问': 'q', '预设回答': 'ans', '易错点 / 考点': 'exam',
          '易错点/考点': 'exam', '过渡': 'trans'}
SZ_RE = re.compile(r'^\*\*【思政落点\s*(\d+)】\*\*\s*(.*)$')


def inline(t):
    t = H.escape(t)
    t = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', t)
    return t


def md_to_html(md, notes=False):
    out, in_table = [], False
    in_quote = False
    for raw in md.split('\n'):
        line = raw.rstrip()
        m = re.match(r'^###\s*【(\d+\.\d+)】(.*?)（\s*(\d+(?:\.\d+)?)\s*分钟\s*）\s*$', line)
        if m:
            if in_quote: out.append('</blockquote>'); in_quote = False
            if in_table: out.append('</table>'); in_table = False
            anchor = m.group(1).replace('.', '-')
            out.append('<div class="pageblock"><h3 id="p%s">【%s】%s（%s 分钟）</h3>'
                       % (anchor, m.group(1), H.escape(m.group(2)), m.group(3)))
            if notes:
                out.append('<div class="note">□ 已讲　□ 需回看　　课堂记录：______________________________________</div>')
            continue
        if line.startswith('> '):
            body = line[2:]
            cls = ''
            if body.startswith('**口播**'):
                cls = 'speak'
                body = re.sub(r'^\*\*口播\*\*[：:]\s*', '', body)
            if not in_quote:
                out.append('<blockquote class="%s">' % cls); in_quote = True
            out.append('<p>%s</p>' % inline(body))
            continue
        if in_quote:
            out.append('</blockquote>'); in_quote = False
        sz = SZ_RE.match(line)
        if sz:
            out.append('<blockquote class="sz"><p><strong>【思政落点 %s】</strong>%s</p></blockquote>'
                       % (sz.group(1), inline(sz.group(2))))
            continue
        lm = re.match(r'^\*\*(板书|提问|预设回答|易错点\s*/\s*考点|过渡)\*\*[：:]\s*(.*)$', line)
        if lm:
            cls = LABELS.get(lm.group(1).replace(' ', ''), 'q') if lm.group(1) != '易错点 / 考点' else 'exam'
            cls = LABELS.get(lm.group(1), cls)
            out.append('<blockquote class="%s"><p><strong>%s：</strong>%s</p></blockquote>'
                       % (cls, H.escape(lm.group(1)), inline(lm.group(2))))
            continue
        if line.startswith('#'):
            lvl = len(line) - len(line.lstrip('#'))
            txt = inline(line.lstrip('# ').strip())
            if lvl == 1:
                out.append('<h1>%s</h1>' % txt)
            elif lvl == 2:
                out.append('<h2>%s</h2>' % txt)
            else:
                out.append('<h3>%s</h3>' % txt)
            continue
        if line.startswith('|'):
            cells = [c.strip() for c in line.strip('|').split('|')]
            if set(''.join(cells)) <= set('-: '):
                continue
            if not in_table:
                out.append('<table>'); in_table = True
                out.append('<tr>' + ''.join('<th>%s</th>' % inline(c) for c in cells) + '</tr>')
            else:
                out.append('<tr>' + ''.join('<td>%s</td>' % inline(c) for c in cells) + '</tr>')
            continue
        if in_table:
            out.append('</table>'); in_table = False
        if line.strip() in ('---', '***'):
            out.append('<hr>'); continue
        if line.strip():
            out.append('<p>%s</p>' % inline(line))
    for flag, closer in ((in_quote, '</blockquote>'), (in_table, '</table>')):
        if flag:
            out.append(closer)
    out.append('</div>')
    return '\n'.join(out)


def build(chaps, title, sub, notes=False, cover=True):
    body = []
    body.append('<html><head><meta charset="utf-8"><style>%s</style></head><body>' % CSS)
    body.append('<div class="cover"><h1>%s</h1><p>%s</p><p>广东金融学院 计算机学院 ｜ 周宇文</p>'
                '<p style="margin-top:20mm;color:#a0aec0">讲稿可照读版 ｜ 由课件逐页撰写</p></div>'
                % (H.escape(title), H.escape(sub)))
    for c in chaps:
        md = open(os.path.join(BASE, CH[c]), encoding='utf-8').read()
        body.append('<h1>%s</h1><p style="color:#718096">%s</p>' % (TITLE[c], SUB[c]))
        body.append(md_to_html(md, notes))
    body.append('</body></html>')
    return '\n'.join(body)


if __name__ == '__main__':
    jobs = [(3, 3, '第2章-讲稿-教材精读增强版-打印版', False),
            (3, 3, '第2章-讲稿-教材精读增强版-备课批注版', True)]
    for a, b, name, notes in jobs:
        chaps = list(range(a, b + 1))
        title = '《软件项目管理》讲稿 · 教材精读增强版'
        html = build(chaps, title, SUB[3], notes)
        p = os.path.join(OUT, name + '.html')
        open(p, 'w', encoding='utf-8').write(html)
        print('已生成', os.path.basename(p))
