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

将模板源目录纳入 pipeline（复制，不删除原目录）。

流程：
1. 校验必需文件
2. 调用 identify_template.py（颁发/校准身份，写回源目录）
3. 读取更新后的 __teacher__.json，拼出目标路径
4. 复制到 templates/{folder_name}/v{N}/
5. 重建 template-index.json

用法：
    python3 move_template_task.py <模板目录> [目标根目录]
"""
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DEFAULT_TARGET = ROOT / 'templates'
IDENTIFY_SCRIPT = ROOT / 'scripts' / 'identify_template.py'
INDEX_SCRIPT = ROOT / 'scripts' / 'build_template_index.py'
REQUIRED_FILES = [
    '__demo__.html', '__student__.json', '__teacher__.json',
    '__student-view__.html', '__teacher-view__.html',
]


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


def sanitize_name(name: str) -> str:
    return re.sub(r'[/\\ ]', '_', str(name).strip())


def get_latest_version_num(folder: Path) -> int:
    """返回 folder 下最大的版本号，没有则返回 0"""
    if not folder.exists():
        return 0
    max_v = 0
    for d in folder.iterdir():
        if d.is_dir():
            m = re.match(r'^v(\d+)$', d.name)
            if m:
                max_v = max(max_v, int(m.group(1)))
    return max_v


def main():
    if len(sys.argv) < 2:
        print('用法: python3 move_template_task.py <模板目录> [目标根目录]')
        sys.exit(1)

    source_dir = Path(sys.argv[1]).expanduser().resolve()
    target_root = Path(sys.argv[2]).expanduser().resolve() if len(sys.argv) > 2 else DEFAULT_TARGET

    if not source_dir.is_dir():
        print(f'❌ 目录不存在: {source_dir}')
        sys.exit(1)

    # 1. 校验必需文件
    for filename in REQUIRED_FILES:
        if not (source_dir / filename).exists():
            print(f'❌ 缺少必需文件: {filename}')
            sys.exit(1)

    # 2. 颁发/校准身份（写回源目录的 __teacher__.json）
    print('\n── 身份认证 ────────────────────────────────')
    subprocess.run([sys.executable, str(IDENTIFY_SCRIPT), str(source_dir)], check=True)

    # 3. 读取更新后的身份信息
    teacher = load_json(source_dir / '__teacher__.json')
    category = teacher.get('任务类别', '').upper()
    number = teacher.get('任务编号', '100')
    name = sanitize_name(teacher.get('任务名称', 'untitled'))

    folder_name = f'{category.lower()}{number}_{name}'
    next_version = get_latest_version_num(target_root / folder_name) + 1
    version_str = f'v{next_version}'
    target_dir = target_root / folder_name / version_str

    if target_dir.exists():
        print(f'❌ 目标目录已存在（重复操作？）: {target_dir}')
        sys.exit(1)

    # 4. 复制到 templates/{folder}/v{N}/
    print(f'\n── 复制文件 ────────────────────────────────')
    target_root.mkdir(parents=True, exist_ok=True)
    shutil.copytree(str(source_dir), str(target_dir))
    print(f'✅ 已复制到: {target_dir}')

    # 5. 重建 index
    print(f'\n── 重建索引 ────────────────────────────────')
    subprocess.run([sys.executable, str(INDEX_SCRIPT)], check=True)


if __name__ == '__main__':
    main()
