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


def esc(value):
    return html.escape(str(value if value is not None else ""))


def render_tags(items):
    return ''.join(f'<span class="tag">{esc(item)}</span>' for item in items)


def render_list(items):
    return ''.join(f'<div class="list-item">{esc(item)}</div>' for item in items)


def render_issues(items):
    blocks = []
    for item in items:
        card = item.get('卡点', '') if isinstance(item, dict) else ''
        solution = item.get('解决方案', '') if isinstance(item, dict) else ''
        blocks.append('<div class="list-item issue">' f'<strong>卡点</strong>{esc(card)}' f'<strong>解决方案</strong>{esc(solution)}' '</div>')
    return ''.join(blocks)


def guess_preview_file(input_path: Path):
    folder = input_path.parent
    for name in ['__demo__.html', 'example.html', 'index.html', 'preview.html']:
        candidate = folder / name
        if candidate.exists() and candidate.name != input_path.name:
            return candidate.name
    return ''


def render_html(data, preview_file=''):
    title = f"{data.get('任务类别', '')}{data.get('任务编号', '')} · {data.get('任务名称', '')}".strip(' ·')
    iframe_html = f'<div class="preview-card"><div class="preview-head"><h2>作品预览</h2></div><iframe src="{esc(preview_file)}" title="作品预览"></iframe></div>' if preview_file else '<div class="preview-card empty"><div class="preview-head"><h2>作品预览</h2></div><div class="empty-box">当前文件夹下没有找到 example.html / index.html / preview.html</div></div>'
    return f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>{esc(title or '教师任务查看页')}</title>
  <style>
    * {{ box-sizing: border-box; }}
    body {{ margin: 0; font-family: "PingFang SC", "Microsoft YaHei", sans-serif; background: #f4f7fb; color: #24324a; }}
    .page {{ max-width: 1400px; margin: 0 auto; padding: 20px; }}
    .hero {{ background: linear-gradient(135deg,#5f82ff 0%,#8c74ff 100%); color: #fff; border-radius: 24px; padding: 22px 24px; box-shadow: 0 16px 36px rgba(92,108,192,.22); }}
    .hero h1 {{ margin: 0; font-size: 28px; }}
    .hero p {{ margin: 8px 0 0; opacity: .92; font-size: 14px; }}
    .layout {{ margin-top: 18px; display: grid; grid-template-columns: 360px minmax(0,1fr); gap: 16px; align-items: start; }}
    .sidebar {{ display: grid; gap: 16px; }}
    .card, .preview-card {{ background: #fff; border: 1px solid #e7eefc; border-radius: 20px; padding: 18px; box-shadow: 0 10px 24px rgba(100,122,166,.08); }}
    .card h2, .preview-head h2 {{ margin: 0 0 12px; font-size: 18px; color: #314a96; }}
    .meta-grid {{ display: grid; grid-template-columns: 1fr; gap: 10px; }}
    .meta-item {{ background: #f8faff; border: 1px solid #e7eefc; border-radius: 14px; padding: 12px; }}
    .meta-item .label {{ font-size: 12px; color: #7a89ad; margin-bottom: 6px; }}
    .meta-item .value {{ font-size: 14px; color: #24324a; font-weight: 700; }}
    .tags {{ display: flex; flex-wrap: wrap; gap: 8px; }}
    .tag {{ display: inline-flex; align-items: center; padding: 7px 12px; border-radius: 999px; background: #edf2ff; color: #4c65c3; font-size: 13px; font-weight: 700; }}
    .list {{ display: grid; gap: 10px; }}
    .list-item {{ background: #f8faff; border: 1px solid #e7eefc; border-radius: 14px; padding: 12px; line-height: 1.7; font-size: 14px; color: #60708b; }}
    .issue {{ border-left: 4px solid #8c74ff; background: #faf8ff; }}
    .issue strong {{ color: #314a96; display: block; margin: 6px 0; }}
    iframe {{ width: 100%; height: 900px; border: 1px solid #dfe7fb; border-radius: 16px; background: #fff; display: block; }}
    .empty-box {{ background: #f8faff; border: 1px dashed #cfdcff; border-radius: 14px; padding: 24px; color: #7a89ad; line-height: 1.8; }}
    @media (max-width: 960px) {{ .layout {{ grid-template-columns: 1fr; }} iframe {{ height: 420px; }} }}
  </style>
</head>
<body>
  <div class="page">
    <section class="hero">
      <h1>{esc(title or '教师任务查看页')}</h1>
      <p>这是根据教师 JSON 自动生成的可视化查看页，左边快速扫读，右边直接看作品预览。</p>
    </section>
    <section class="layout">
      <div class="sidebar">
        <div class="card"><h2>基础信息</h2><div class="meta-grid"><div class="meta-item"><div class="label">主能力标签</div><div class="value">{esc(data.get('主能力标签', '—'))}</div></div><div class="meta-item"><div class="label">任务类型标签</div><div class="value">{esc(data.get('任务类型标签', '—'))}</div></div></div></div>
        <div class="card"><h2>适合学生类型</h2><div class="tags">{render_tags(data.get('适合学生类型', []))}</div></div>
        <div class="card"><h2>训练重点</h2><div class="list">{render_list(data.get('训练重点', []))}</div></div>
        <div class="card"><h2>卡点和解决方案</h2><div class="list">{render_issues(data.get('卡点和解决方案', []))}</div></div>
        <div class="card"><h2>可拓展方向</h2><div class="list">{render_list(data.get('可拓展方向', []))}</div></div>
        <div class="card"><h2>课后作业</h2><div class="list">{render_list(data.get('课后作业', []))}</div></div>
      </div>
      {iframe_html}
    </section>
  </div>
</body>
</html>'''


def main():
    if len(sys.argv) < 2:
        print('用法: python3 render_teacher_view.py <输入json> [输出html]')
        sys.exit(1)
    input_path = Path(sys.argv[1]).expanduser().resolve()
    output_path = Path(sys.argv[2]).expanduser().resolve() if len(sys.argv) > 2 else input_path.parent / '__teacher-view__.html'
    with input_path.open('r', encoding='utf-8') as f:
        data = json.load(f)
    output_path.write_text(render_html(data, guess_preview_file(input_path)), encoding='utf-8')
    print(f'已生成: {output_path}')


if __name__ == '__main__':
    main()
