#!/usr/bin/env python3
import html
import json
import subprocess
import sys
from pathlib import Path

REQUIRED_BASE_FILES = ['__demo__.html', '__student__.json', '__teacher__.json']
REQUIRED_STUDENT_KEYS = ['任务标题', '一句话说明', '步骤', '评价目标', '示例区标题', '示例页面文件', '小提示']
REQUIRED_TEACHER_KEYS = ['任务类别', '任务编号', '任务名称', '主能力标签', '任务类型标签', '适合学生类型', '训练重点', '卡点和解决方案', '可拓展方向', '课后作业']
ROOT = Path(__file__).resolve().parent

INDEX_TEMPLATE = """\
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{title}</title>
  <style>
    * {{ box-sizing: border-box; }}
    body {{
      margin: 0;
      padding: 24px;
      font-family: monospace;
      background: #f6f8fc;
      color: #1f2937;
    }}
    .grid {{
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      align-items: start;
    }}
    h2 {{
      margin: 0 0 10px;
      font-size: 18px;
    }}
    pre {{
      margin: 0;
      white-space: pre-wrap;
      word-break: break-word;
      background: #ffffff;
      border: 1px solid #dbe3f0;
      border-radius: 12px;
      padding: 16px;
      line-height: 1.7;
    }}
  </style>
</head>
<body>
<!--
  [AI 编辑说明]
  这是学生作品的主文件。当你开始编辑时：
  1. 先删除 <body> 内所有现有内容（包括本注释）
  2. 根据参考材料（__demo__.html 等 __XXX__ 文件）重新制作学生作品
  __XXX__ 文件只读，不要修改。
-->
  <div class="grid">
    <section>
      <h2>评价目标</h2>
      <pre>{goals_json}</pre>
    </section>
    <section>
      <h2>步骤</h2>
      <pre>{steps_json}</pre>
    </section>
  </div>

  <script type="application/json" id="task-data">
{raw_task_json}
  </script>
</body>
</html>
"""


def load_json(path):
    with path.open('r', encoding='utf-8') as f:
        return json.load(f)


def check_keys(data, keys, name):
    missing = [k for k in keys if k not in data]
    if missing:
        raise ValueError(f'{name} 缺少字段: {", ".join(missing)}')


def validate_folder(source_dir: Path):
    for filename in REQUIRED_BASE_FILES:
        if not (source_dir / filename).exists():
            raise FileNotFoundError(f'缺少必需文件: {filename}')
    student = load_json(source_dir / '__student__.json')
    teacher = load_json(source_dir / '__teacher__.json')
    check_keys(student, REQUIRED_STUDENT_KEYS, '__student__.json')
    check_keys(teacher, REQUIRED_TEACHER_KEYS, '__teacher__.json')


def render_index_page(source_dir: Path):
    student = load_json(source_dir / '__student__.json')
    task_json = json.dumps(student, ensure_ascii=False, indent=2)
    goals_json = json.dumps(student.get('评价目标', []), ensure_ascii=False, indent=2)
    steps_json = json.dumps(student.get('步骤', []), ensure_ascii=False, indent=2)
    content = INDEX_TEMPLATE.format(
        title=html.escape(student.get('任务标题', '未命名任务')),
        goals_json=html.escape(goals_json),
        steps_json=html.escape(steps_json),
        raw_task_json=task_json,
    )
    out = source_dir / 'index.html'
    out.write_text(content, encoding='utf-8')
    print(f'已生成: {out}')


def main():
    if len(sys.argv) < 2:
        print('用法: python3 build_template_views.py <已有文件夹>')
        sys.exit(1)

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

    subprocess.run(['python3', str(ROOT / 'render_student_page.py'), str(source_dir / '__student__.json'), str(source_dir / '__student-view__.html')], check=True)
    subprocess.run(['python3', str(ROOT / 'render_teacher_view.py'), str(source_dir / '__teacher__.json'), str(source_dir / '__teacher-view__.html')], check=True)
    render_index_page(source_dir)

    print(f'已在原文件夹生成: {source_dir}')
    print('已生成 __student-view__.html、__teacher-view__.html、index.html')


if __name__ == '__main__':
    main()
