"""Week 5: 迴圈基礎 — for-each, for-range, while"""

from checker._core import check_value
from checker._feedback import (
    show_pass, show_fail, show_type_error, show_summary, show_error,
)
from checker._tracking import init_tracking, log_attempt, is_blocked

_WEEK = "05"
_student_id = None
_attempts = {"Q1": 0, "Q2": 0, "Q3": 0}
_results = {}

# --- 答案 hash ---
# Q1: sum of [28, 30, 27, 31, 29, 26, 32] = 203
_Q1_HASH = "4621c1d55fa4e86ce0dae4288302641baac86dd53f76227c892df9d300682d41"
# Q2: count even indices in range(0,10,2) = 5
_Q2_HASH = "ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d"
# Q3: water_level after while loop = 10
_Q3_HASH = "4a44dc15364204a80fe80e9039455cc1608281820fe2b24f1e5233ade6af1dd5"

# --- 提示 ---
_Q1_HINTS = [
    "用 for t in temperatures: 逐一取出溫度",
    "用 total += t 累加每一天的溫度",
    "記得先設 total = 0 再開始迴圈",
]
_Q2_HINTS = [
    "range(0, 10, 2) 產生 0, 2, 4, 6, 8",
    "每次迴圈 water_count += 1",
    "想想看：0, 2, 4, 6, 8 共幾個數字？",
]
_Q3_HINTS = [
    "while water_level > 20: 表示水位大於 20 才繼續",
    "每次迴圈 water_level -= 15",
    "追蹤：100→85→70→55→40→25→10，到 10 時不再 > 20",
]


def init(student_id):
    """初始化：輸入學號並嘗試連線追蹤系統"""
    global _student_id
    _student_id = str(student_id).strip()
    if not _student_id or _student_id == "在這裡輸入你的學號":
        print("⚠️ 請輸入你的學號！例如：week05.init('M1234567')")
        return
    result = init_tracking(_student_id, context="homework")
    if result == "blocked":
        return
    if result == "not_in_roster":
        print(f"⚠️ 學號 {_student_id} 不在名單中，請確認是否輸入正確。")
    print(f"✅ 學號 {_student_id} 已登記，開始作答吧！")


def check_q1(total):
    """Q1: 檢查溫度總和（for-each 累加）"""
    if is_blocked():
        return
    label = "Q1 溫度加總"
    _attempts["Q1"] += 1
    try:
        passed, status, got, expected = check_value(total, _Q1_HASH, int)
        if passed:
            show_pass(label)
            _results["Q1"] = True
        elif status == "type_error":
            show_type_error(label, got, expected)
            _results["Q1"] = False
        else:
            show_fail(label, "總和不正確", _Q1_HINTS, _attempts["Q1"])
            _results["Q1"] = False
        log_attempt(_student_id, _WEEK, "Q1", _results.get("Q1", False),
                    submitted_code=repr(total))
    except Exception as e:
        show_error(label, str(e))
        _results["Q1"] = False


def check_q2(water_count):
    """Q2: 檢查澆水次數（for-range 計數）"""
    if is_blocked():
        return
    label = "Q2 澆水次數"
    _attempts["Q2"] += 1
    try:
        passed, status, got, expected = check_value(water_count, _Q2_HASH, int)
        if passed:
            show_pass(label)
            _results["Q2"] = True
        elif status == "type_error":
            show_type_error(label, got, expected)
            _results["Q2"] = False
        else:
            show_fail(label, "次數不正確", _Q2_HINTS, _attempts["Q2"])
            _results["Q2"] = False
        log_attempt(_student_id, _WEEK, "Q2", _results.get("Q2", False),
                    submitted_code=repr(water_count))
    except Exception as e:
        show_error(label, str(e))
        _results["Q2"] = False


def check_q3(water_level):
    """Q3: 檢查最終水位（while 迴圈）"""
    if is_blocked():
        return
    label = "Q3 水位模擬"
    _attempts["Q3"] += 1
    try:
        passed, status, got, expected = check_value(water_level, _Q3_HASH, int)
        if passed:
            show_pass(label)
            _results["Q3"] = True
        elif status == "type_error":
            show_type_error(label, got, expected)
            _results["Q3"] = False
        else:
            show_fail(label, "最終水位不正確", _Q3_HINTS, _attempts["Q3"])
            _results["Q3"] = False
        log_attempt(_student_id, _WEEK, "Q3", _results.get("Q3", False),
                    submitted_code=repr(water_level))
    except Exception as e:
        show_error(label, str(e))
        _results["Q3"] = False


def check_all():
    """顯示作業總結"""
    if not _results:
        print("⚠️ 你還沒有檢查任何題目，請先執行 check_q1()、check_q2()、check_q3()。")
        return
    show_summary(_results)
