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

将旧版平铺结构迁移到版本化结构：
  templates/{folder}/*.html  →  templates/{folder}/v1/*.html

同时为没有 _id 的模板颁发 ID，写入 __teacher__.json。

用法：
    python3 scripts/migrate_templates.py [--dry-run]
"""
import json
import re
import secrets
import shutil
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = ROOT / 'templates'
INDEX_SCRIPT = ROOT / 'scripts' / 'build_template_index.py'


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


def save_json(path: Path, data: dict):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')


def gen_id() -> str:
    return secrets.token_hex(4)


def has_version_subdir(folder: Path) -> bool:
    for d in folder.iterdir():
        if d.is_dir() and re.match(r'^v\d+$', d.name):
            return True
    return False


def main():
    dry_run = '--dry-run' in sys.argv
    if dry_run:
        print('🔍 DRY RUN 模式，不实际修改文件\n')

    if not TEMPLATES_DIR.exists():
        print('❌ templates/ 目录不存在')
        sys.exit(1)

    folders = sorted(d for d in TEMPLATES_DIR.iterdir() if d.is_dir())
    migrated = 0

    for folder in folders:
        if has_version_subdir(folder):
            print(f'✓ 跳过（已版本化）: {folder.name}')
            continue

        # 列出所有直接子文件（排除目录）
        files = [f for f in folder.iterdir() if f.is_file()]
        if not files:
            print(f'⚠️  空目录，跳过: {folder.name}')
            continue

        teacher_path = folder / '__teacher__.json'
        teacher = load_json(teacher_path)

        # 补充 _id
        if not teacher.get('_id'):
            teacher['_id'] = gen_id()
            print(f'🆔 颁发 ID {teacher["_id"]}: {folder.name}')

        # 补充 _version
        if not teacher.get('_version'):
            teacher['_version'] = 1

        if not dry_run:
            # 先写回 __teacher__.json
            save_json(teacher_path, teacher)

            # 创建 v1/ 并移动所有文件
            v1_dir = folder / 'v1'
            v1_dir.mkdir(exist_ok=True)
            for f in files:
                shutil.move(str(f), str(v1_dir / f.name))

        print(f'📦 迁移: {folder.name}  →  {folder.name}/v1/')
        migrated += 1

    print(f'\n{"[DRY RUN] " if dry_run else ""}共迁移 {migrated} 个模板')

    if not dry_run and migrated > 0:
        import subprocess
        subprocess.run(['python3', str(INDEX_SCRIPT)], check=True)
        print('✅ 索引已重建')


if __name__ == '__main__':
    main()
