"""Colab 友善的 HTML 回饋訊息"""

import random

_PASS_MESSAGES = [
    "太棒了！答對了！",
    "正確！做得好！",
    "完全正確！繼續加油！",
    "答對囉！你很厲害！",
    "恭喜答對！",
]

_ENCOURAGEMENTS = [
    "再想想看，你可以的！",
    "加油！快要答對了！",
    "別灰心，再試一次！",
    "仔細看看題目，答案就在裡面！",
]


def _display_html(html):
    """在 Colab/Jupyter 中顯示 HTML，純終端機則用文字"""
    try:
        from IPython.display import display, HTML
        display(HTML(html))
    except ImportError:
        # 非 notebook 環境，印出純文字
        import re
        text = re.sub(r"<[^>]+>", "", html)
        print(text)


def show_pass(question_label):
    """顯示通過訊息"""
    msg = random.choice(_PASS_MESSAGES)
    html = f"""
    <div style="padding:12px 16px;border-radius:8px;background:#d4edda;border:1px solid #c3e6cb;margin:8px 0;">
        <span style="font-size:20px;">✅</span>
        <strong style="color:#155724;margin-left:8px;">{question_label} — {msg}</strong>
    </div>
    """
    _display_html(html)


def show_fail(question_label, message, hints=None, attempt=0):
    """顯示失敗訊息，含漸進式提示"""
    hint_html = ""
    if hints and attempt > 0:
        # 每多嘗試一次，多顯示一個提示（最多全部）
        n_hints = min(attempt, len(hints))
        hint_items = "".join(f"<li>{h}</li>" for h in hints[:n_hints])
        hint_html = f"""
        <div style="margin-top:8px;padding:8px 12px;background:#fff3cd;border-radius:4px;border:1px solid #ffeeba;">
            <strong style="color:#856404;">💡 提示：</strong>
            <ul style="margin:4px 0 0 0;padding-left:20px;color:#856404;">{hint_items}</ul>
        </div>
        """

    encouragement = random.choice(_ENCOURAGEMENTS)
    html = f"""
    <div style="padding:12px 16px;border-radius:8px;background:#f8d7da;border:1px solid #f5c6cb;margin:8px 0;">
        <span style="font-size:20px;">❌</span>
        <strong style="color:#721c24;margin-left:8px;">{question_label} — {message}</strong>
        <div style="color:#721c24;margin-top:4px;font-size:0.9em;">{encouragement}</div>
        {hint_html}
    </div>
    """
    _display_html(html)


def show_type_error(question_label, got_type, expected_type):
    """顯示型態錯誤訊息"""
    html = f"""
    <div style="padding:12px 16px;border-radius:8px;background:#f8d7da;border:1px solid #f5c6cb;margin:8px 0;">
        <span style="font-size:20px;">⚠️</span>
        <strong style="color:#721c24;margin-left:8px;">{question_label} — 型態錯誤</strong>
        <div style="color:#721c24;margin-top:4px;">
            你的答案型態是 <code>{got_type}</code>，但這題需要的是 <code>{expected_type}</code>
        </div>
    </div>
    """
    _display_html(html)


def show_summary(results):
    """顯示作業總結

    Parameters
    ----------
    results : dict
        {question_label: bool} 的字典
    """
    total = len(results)
    passed = sum(1 for v in results.values() if v)
    pct = int(passed / total * 100) if total > 0 else 0

    if passed == total:
        bg, border, color, icon = "#d4edda", "#c3e6cb", "#155724", "🎉"
        status = "全部通過！太厲害了！"
    elif passed > 0:
        bg, border, color, icon = "#fff3cd", "#ffeeba", "#856404", "💪"
        status = f"通過 {passed}/{total} 題，繼續加油！"
    else:
        bg, border, color, icon = "#f8d7da", "#f5c6cb", "#721c24", "📝"
        status = "還沒有通過的題目，加油！"

    rows = ""
    for label, p in results.items():
        mark = "✅" if p else "❌"
        rows += f"<tr><td style='padding:4px 12px;'>{label}</td><td style='padding:4px 12px;'>{mark}</td></tr>"

    html = f"""
    <div style="padding:16px;border-radius:8px;background:{bg};border:1px solid {border};margin:8px 0;">
        <div style="font-size:20px;margin-bottom:8px;">{icon} <strong style="color:{color};">{status}</strong></div>
        <table style="border-collapse:collapse;color:{color};">
            <tr><th style="padding:4px 12px;text-align:left;">題目</th><th style="padding:4px 12px;">結果</th></tr>
            {rows}
        </table>
        <div style="margin-top:8px;color:{color};font-size:0.9em;">完成度：{pct}%（{passed}/{total}）</div>
    </div>
    """
    _display_html(html)


def show_error(question_label, error_msg):
    """顯示執行錯誤"""
    html = f"""
    <div style="padding:12px 16px;border-radius:8px;background:#f8d7da;border:1px solid #f5c6cb;margin:8px 0;">
        <span style="font-size:20px;">💥</span>
        <strong style="color:#721c24;margin-left:8px;">{question_label} — 程式執行錯誤</strong>
        <div style="color:#721c24;margin-top:4px;"><code>{error_msg}</code></div>
    </div>
    """
    _display_html(html)


def show_function_result(question_label, all_passed, case_results, hints=None, attempt=0):
    """顯示函數測試結果"""
    if all_passed:
        show_pass(question_label)
        return

    total = len(case_results)
    passed = sum(1 for r in case_results if r["passed"])
    errors = [r for r in case_results if not r["passed"]]

    detail_items = ""
    for r in errors[:3]:
        if "error" in r:
            detail_items += f"<li>測試案例 {r['case']}：執行錯誤 — <code>{r['error']}</code></li>"
        else:
            detail_items += f"<li>測試案例 {r['case']}：結果不正確</li>"

    hint_html = ""
    if hints and attempt > 0:
        n_hints = min(attempt, len(hints))
        hint_items = "".join(f"<li>{h}</li>" for h in hints[:n_hints])
        hint_html = f"""
        <div style="margin-top:8px;padding:8px 12px;background:#fff3cd;border-radius:4px;border:1px solid #ffeeba;">
            <strong style="color:#856404;">💡 提示：</strong>
            <ul style="margin:4px 0 0 0;padding-left:20px;color:#856404;">{hint_items}</ul>
        </div>
        """

    encouragement = random.choice(_ENCOURAGEMENTS)
    html = f"""
    <div style="padding:12px 16px;border-radius:8px;background:#f8d7da;border:1px solid #f5c6cb;margin:8px 0;">
        <span style="font-size:20px;">❌</span>
        <strong style="color:#721c24;margin-left:8px;">{question_label} — 通過 {passed}/{total} 個測試案例</strong>
        <ul style="color:#721c24;margin:4px 0 0 0;padding-left:20px;font-size:0.9em;">{detail_items}</ul>
        <div style="color:#721c24;margin-top:4px;font-size:0.9em;">{encouragement}</div>
        {hint_html}
    </div>
    """
    _display_html(html)


def show_exam_result(question_label, passed, score_ratio=None):
    """Exam feedback: no hints, no encouragement. Shows pass/fail and optional score ratio.

    Parameters
    ----------
    question_label : str
        e.g. "Q1 算術運算"
    passed : bool
        Whether the answer is correct
    score_ratio : tuple(int, int) or None
        (passed_count, total_count) for function questions with partial scoring
    """
    if passed:
        html = f"""
        <div style="padding:12px 16px;border-radius:8px;background:#d4edda;border:1px solid #c3e6cb;margin:8px 0;">
            <strong style="color:#155724;">{question_label} -- 正確</strong>
        </div>
        """
    elif score_ratio is not None:
        p, t = score_ratio
        html = f"""
        <div style="padding:12px 16px;border-radius:8px;background:#f8d7da;border:1px solid #f5c6cb;margin:8px 0;">
            <strong style="color:#721c24;">{question_label} -- 通過 {p}/{t} 個測試案例</strong>
        </div>
        """
    else:
        html = f"""
        <div style="padding:12px 16px;border-radius:8px;background:#f8d7da;border:1px solid #f5c6cb;margin:8px 0;">
            <strong style="color:#721c24;">{question_label} -- 不正確</strong>
        </div>
        """
    _display_html(html)
