#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把练习题 md 转成题库导入模板 xls（列结构与 importQuestionTemplateNew.xls 一致）。

用法：python3 gen_xls.py <输出.xls> <in1.md> [in2.md ...]
模板列（A–T）：
  A 目录 / B 题目类型 / C 自定义题型 / D 大题题干 / E 小题题型 / F 小题题干 /
  G 正确答案 / H 答案解析 / I 难易度 / J 知识点 / K 标签 / L 选项数 / M–T 选项A–H
规则（依模板说明）：
  - 单选题：选项数=4，选项写 A–D 列，正确答案为字母；
  - 判断题：选项数=2，A 列"正确"、B 列"错误"，正确答案为 A（对）或 B（错）；
  - 目录按 "/课程/章节" 两级填写；不写说明行（模板要求导入前删除说明行）。
"""
import re, sys, os
import xlwt
from xlwt import easyxf

HEADER = ['目录', '题目类型', '自定义题型', '大题题干', '小题题型', '小题题干',
          '正确答案', '答案解析', '难易度', '知识点', '标签', '选项数',
          '选项A', '选项B', '选项C', '选项D', '选项E', '选项F', '选项G', '选项H']

COURSE_DIR = '软件测试课程设计'
Q_RE = re.compile(r'^\s*(\d+)\.【(单选题|判断题)】(.*)$')


def parse_md(path):
    """返回 (章名, [题目 dict])"""
    lines = open(path, encoding='utf-8').read().splitlines()
    title = next((l for l in lines if l.startswith('# ')), '')
    m = re.search(r'第\s*(\d+)\s*章\s*([^·｜|]+)', title)
    chap = f'第{m.group(1)}章 {m.group(2).strip()}' if m else os.path.basename(path)
    blocks, cur = [], None
    for ln in lines:
        mm = Q_RE.match(ln)
        if mm:
            if cur:
                blocks.append(cur)
            cur = {'no': int(mm.group(1)), 'type': mm.group(2), 'stem': mm.group(3).strip(),
                   'opts': [], 'fields': {}}
            continue
        if cur is None:
            continue
        s = ln.strip()
        if not s:
            continue
        mo = re.match(r'^([A-D])\.(.*)$', s)
        mf = re.match(r'^(答案|难易程度|答案解析|知识点|课程目标)：(.*)$', s)
        if mf:
            cur['fields'][mf.group(1)] = mf.group(2).strip()
        elif mo and cur['type'] == '单选题':
            cur['opts'].append((mo.group(1), mo.group(2).strip()))
        elif not cur['fields']:
            cur['stem'] += s
    if cur:
        blocks.append(cur)
    return chap, blocks


def build(out_path, chap, blocks):
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('课程题库')
    hdr = easyxf('font: bold on, height 240; align: horiz center, vert center; '
                 'pattern: pattern solid, fore_colour gray25; borders: left thin, right thin, top thin, bottom thin')
    body = easyxf('align: vert top, wrap on')
    center = easyxf('align: horiz center, vert top')
    for c, h in enumerate(HEADER):
        ws.write(0, c, h, hdr)
        ws.col(c).width = 256 * (10 if c in (0, 1, 6, 8, 11) else 40)
    ws.col(3).width = 256 * 60      # 大题题干
    ws.col(7).width = 256 * 55      # 答案解析
    ws.col(9).width = 256 * 28      # 知识点
    r = 1
    for b in blocks:
        f = b['fields']
        goal = f.get('课程目标', '')
        gm = re.search(r'课程目标\s*(\d)', goal)
        ans_text = f.get('答案解析', '')
        if gm:
            ans_text = f'{ans_text}（对应课程目标{gm.group(1)}）'
        row = {
            0: f'/{COURSE_DIR}/{chap}',
            1: b['type'],
            3: b['stem'],
            7: ans_text,
            8: f.get('难易程度', '中'),
            9: f.get('知识点', ''),
        }
        if b['type'] == '单选题':
            row[6] = f.get('答案', '')
            row[11] = 4
            for i, (letter, text) in enumerate(b['opts']):
                row[12 + i] = text
        else:
            row[6] = 'A' if f.get('答案') == '对' else 'B'
            row[11] = 2
            row[12], row[13] = '正确', '错误'
        for c, v in row.items():
            ws.write(r, c, v, center if c in (1, 6, 8, 11) else body)
        r += 1
    wb.save(out_path)
    return r - 1


if __name__ == '__main__':
    out = sys.argv[1]
    srcs = sys.argv[2:]
    if len(srcs) == 1:
        chap, blocks = parse_md(srcs[0])
        n = build(out, chap, blocks)
    else:
        # 多文件合并：逐题写进同一个 sheet
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('课程题库')
        hdr = easyxf('font: bold on, height 240; align: horiz center, vert center; '
                     'pattern: pattern solid, fore_colour gray25; borders: left thin, right thin, top thin, bottom thin')
        body = easyxf('align: vert top, wrap on')
        center = easyxf('align: horiz center, vert top')
        for c, h in enumerate(HEADER):
            ws.write(0, c, h, hdr)
            ws.col(c).width = 256 * (10 if c in (0, 1, 6, 8, 11) else 40)
        ws.col(3).width = 256 * 60
        ws.col(7).width = 256 * 55
        ws.col(9).width = 256 * 28
        r = 1
        for src in srcs:
            chap, blocks = parse_md(src)
            for b in blocks:
                f = b['fields']
                gm = re.search(r'课程目标\s*(\d)', f.get('课程目标', ''))
                ans_text = f.get('答案解析', '')
                if gm:
                    ans_text = f'{ans_text}（对应课程目标{gm.group(1)}）'
                row = {0: f'/{COURSE_DIR}/{chap}', 1: b['type'], 3: b['stem'], 7: ans_text,
                       8: f.get('难易程度', '中'), 9: f.get('知识点', '')}
                if b['type'] == '单选题':
                    row[6] = f.get('答案', '')
                    row[11] = 4
                    for i, (letter, text) in enumerate(b['opts']):
                        row[12 + i] = text
                else:
                    row[6] = 'A' if f.get('答案') == '对' else 'B'
                    row[11] = 2
                    row[12], row[13] = '正确', '错误'
                for c, v in row.items():
                    ws.write(r, c, v, center if c in (1, 6, 8, 11) else body)
                r += 1
        wb.save(out)
        n = r - 1
    print(f'已生成：{out}（{n} 题）')
