#!/usr/bin/env python3
"""
build_template_index.py

扫描 templates/ 目录，为每个模板读取最新版本子目录（v{N}/）中的
__teacher__.json 和 __student__.json，生成 template-index.json 和 template-index.md。

index 以 _id 为主键（flat 结构），每条记录包含版本号。
"""
import json
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

ROOT = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = ROOT / 'templates'
OUTPUT_JSON = ROOT / 'template-index.json'
OUTPUT_MD = ROOT / 'template-index.md'


def read_json(path: Path) -> dict:
    try:
        return json.loads(path.read_text(encoding='utf-8'))
    except Exception:
        return {}


def parse_folder_name(name: str):
    m = re.match(r'^([a-zA-Z]+)(\d+)_(.+)$', name)
    if m:
        return m.group(1).upper(), str(int(m.group(2))), m.group(3)
    return None, None, None


def get_latest_version_dir(folder: Path):
    """返回最新版本子目录 Path 和版本号 int，没有则返回 (None, 0)"""
    max_v = 0
    result = None
    for d in folder.iterdir():
        if d.is_dir():
            m = re.match(r'^v(\d+)$', d.name)
            if m:
                v = int(m.group(1))
                if v > max_v:
                    max_v = v
                    result = d
    return result, max_v


def get_entry_file(version_dir: Path) -> Optional[Path]:
    for name in ['index.html', '__demo__.html', '__student-view__.html']:
        if (version_dir / name).exists():
            return version_dir / name
    return None


def main():
    templates = {}   # { _id: record }
    items_for_md = []

    for folder in sorted(TEMPLATES_DIR.iterdir() if TEMPLATES_DIR.exists() else []):
        if not folder.is_dir():
            continue

        series, number, _ = parse_folder_name(folder.name)
        if not series:
            continue

        version_dir, version_num = get_latest_version_dir(folder)
        if not version_dir:
            continue

        teacher = read_json(version_dir / '__teacher__.json')
        student = read_json(version_dir / '__student__.json')

        tid = teacher.get('_id', '').strip()
        if not tid:
            continue

        name = teacher.get('任务名称') or student.get('任务标题', '')
        一句话 = student.get('一句话说明', '')
        能力标签 = teacher.get('主能力标签', '')
        类型标签 = teacher.get('任务类型标签', '')

        keywords = list(dict.fromkeys(filter(None, [
            folder.name,
            一句话,
            *teacher.get('适合学生类型', []),
            *teacher.get('训练重点', []),
            name,
            能力标签,
            类型标签,
        ])))

        entry = get_entry_file(version_dir)

        all_files = list(version_dir.rglob('*'))
        folder_mtime = max(
            (f.stat().st_mtime for f in all_files if f.is_file()),
            default=0
        )
        updated_at = datetime.fromtimestamp(folder_mtime, tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')

        version_str = f'v{version_num}'

        record = {
            'id': tid,
            '系列': series,
            '编号': number,
            '名称': name,
            '文件夹名': folder.name,
            'version': version_str,
            '路径': str(version_dir.relative_to(ROOT)),
            '入口文件': str(entry.relative_to(ROOT)) if entry else '',
            '一句话说明': 一句话,
            '主能力标签': 能力标签,
            '任务类型标签': 类型标签,
            '关键词': keywords,
            'updated_at': updated_at,
        }

        templates[tid] = record
        items_for_md.append(record)

    index_updated_at = datetime.now(tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
    output = {'index_updated_at': index_updated_at, 'templates': templates}
    OUTPUT_JSON.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')

    items_for_md.sort(key=lambda x: (x['系列'], int(x['编号'])))
    lines = ['# 模板索引', '', '每次 templates 内模板有变化后，都应重新运行本脚本。', '']
    for item in items_for_md:
        lines.append(f"## {item['系列']}{item['编号']} {item['名称']}")
        lines.append(f"- ID：{item['id']}")
        lines.append(f"- 版本：{item['version']}")
        lines.append(f"- 路径：{item['路径']}")
        lines.append(f"- 入口文件：{item['入口文件']}")
        lines.append(f"- 主能力标签：{item['主能力标签']}")
        lines.append(f"- 任务类型标签：{item['任务类型标签']}")
        if item['关键词']:
            lines.append(f"- 关键词：{', '.join(str(k) for k in item['关键词'])}")
        lines.append('')

    OUTPUT_MD.write_text('\n'.join(lines), encoding='utf-8')
    print(f'已生成: {OUTPUT_JSON}（共 {len(templates)} 条）')
    print(f'已生成: {OUTPUT_MD}')


if __name__ == '__main__':
    main()
