#!/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_steps(steps):
    blocks = []
    for idx, item in enumerate(steps, start=1):
        blocks.append(f'''<div class="task-item"><div class="item-top"><span class="num">{idx}</span><span>{esc(item.get('标题', '步骤'))}</span></div><div class="item-body">{esc(item.get('说明', ''))}</div></div>''')
    return ''.join(blocks)


def render_goals(goals):
    blocks = []
    for item in goals:
        blocks.append(f'''<div class="task-item star-item"><div class="item-top"><span class="num">{esc(item.get('等级', ''))}</span><span>{esc(item.get('等级', ''))}</span></div><div class="item-body">{esc(item.get('说明', ''))}</div></div>''')
    return ''.join(blocks)


def render_tips(tips):
    blocks = []
    for item in tips:
        blocks.append(f'''<div class="tip-item"><div class="tip-title">{esc(item.get('标题', '小提示'))}</div><div class="tip-desc">{esc(item.get('说明', ''))}</div><div class="tip-prompt">参考提示词：{esc(item.get('参考提示词', ''))}</div></div>''')
    return ''.join(blocks)


def main():
    if len(sys.argv) < 2:
        print('用法: python3 render_student_page.py <__student__.json> [输出html] [模板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 / '__student-view__.html'
    template_path = Path(sys.argv[3]).expanduser().resolve() if len(sys.argv) > 3 else Path(__file__).resolve().parent.parent / 'assets' / 'student-template.html'

    data = json.loads(input_path.read_text(encoding='utf-8'))
    template = template_path.read_text(encoding='utf-8')

    folder = input_path.parent
    if (folder / '__任务__.html').exists():
        preview_file = '__任务__.html'
    else:
        preview_file = data.get('示例页面文件', '__demo__.html')

    rendered = (template
        .replace('{{任务标题}}', esc(data.get('任务标题', '未命名任务')))
        .replace('{{一句话说明}}', esc(data.get('一句话说明', '')))
        .replace('{{步骤区域}}', render_steps(data.get('步骤', [])))
        .replace('{{评价目标区域}}', render_goals(data.get('评价目标', [])))
        .replace('{{示例区标题}}', esc(data.get('示例区标题', '示范样例')))
        .replace('{{示例页面文件}}', esc(preview_file))
        .replace('{{小提示区域}}', render_tips(data.get('小提示', [])))
    )

    output_path.write_text(rendered, encoding='utf-8')
    print(f'已生成: {output_path}')


if __name__ == '__main__':
    main()
