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

一键发布脚本：合并 build → move → publish 三个步骤。

传入原始模板目录（或已有 vN/ 目录），自动执行：
  Step 1: build_template_views.py <source_dir>   → 生成/更新 HTML 视图
  Step 2: move_template_task.py <source_dir>     → 创建新版本目录 vN+1/
  Step 3: publish_template.py <templates/xxx/>   → 上传 CDN + 上传 index

用法：
    python3 scripts/release_template.py <模板目录>
"""
import json
import re
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
BUILD_SCRIPT   = ROOT / 'scripts' / 'build_template_views.py'
MOVE_SCRIPT    = ROOT / 'scripts' / 'move_template_task.py'
PUBLISH_SCRIPT = ROOT / 'scripts' / 'publish_template.py'
TEMPLATES_DIR  = ROOT / 'templates'


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 main():
    if len(sys.argv) < 2:
        print('用法: python3 scripts/release_template.py <模板目录>')
        sys.exit(1)

    source_dir = Path(sys.argv[1]).expanduser().resolve()

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

    teacher_path = source_dir / '__teacher__.json'
    if not teacher_path.exists():
        print(f'❌ 找不到 __teacher__.json: {teacher_path}')
        sys.exit(1)

    # ── Step 1: Build HTML views ──────────────────────────────────────────
    print('\n══ Step 1: 生成 HTML 视图 ══════════════════════════════')
    subprocess.run([sys.executable, str(BUILD_SCRIPT), str(source_dir)], check=True)

    # ── Step 2: Move to templates/ ────────────────────────────────────────
    print('\n══ Step 2: 移入 templates/ ═════════════════════════════')
    subprocess.run([sys.executable, str(MOVE_SCRIPT), str(source_dir)], check=True)

    # ── Determine publish target from updated teacher.json ────────────────
    teacher = load_json(teacher_path)
    category = teacher.get('任务类别', '').upper()
    number   = teacher.get('任务编号', '100')
    name     = sanitize_name(teacher.get('任务名称', 'untitled'))
    folder_name = f'{category.lower()}{number}_{name}'
    publish_target = TEMPLATES_DIR / folder_name

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

    # ── Step 3: Publish to CDN ────────────────────────────────────────────
    print('\n══ Step 3: 上传 CDN ════════════════════════════════════')
    subprocess.run([sys.executable, str(PUBLISH_SCRIPT), str(publish_target)], check=True)

    print('\n✅ 发布完成！')
    print(f'   模板目录: {publish_target}')


if __name__ == '__main__':
    main()
