"""Week 6: 進階迴圈技巧 — enumerate, zip, break, continue"""

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 = "06"
_student_id = None
_attempts = {"Q1": 0, "Q2": 0, "Q3": 0}
_results = {}

# --- 答案 hash ---
# Q1: "1.番茄 2.小黃瓜 3.草莓"
_Q1_HASH = "2538e77da2e5d3020845a994783a3416d00cb9152bff3981f62d22d295aa570b"
# Q2: 1200 + 850 + 600 = 2650
_Q2_HASH = "00150bc11aeeaa3cdbdc1e27085b0f6c584c27e05f255e303898dcd12426f110"
# Q3: first temp > 33 at index 2
_Q3_HASH = "d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35"

# --- 提示 ---
_Q1_HINTS = [
    "enumerate(crops, start=1) 會給你 (1, '番茄'), (2, '小黃瓜'), ...",
    "用 f\"{i}.{crop}\" 組合每一項",
    "最後用 .strip() 去掉尾巴的空白，或用 ' '.join() 組合",
]
_Q2_HINTS = [
    "zip(crops, yields) 可以同時走訪兩個 list",
    "for crop, y in zip(crops, yields): total += y",
    "加總三個產量：1200 + 850 + 600",
]
_Q3_HINTS = [
    "用 enumerate(temps) 同時取得 index 和溫度值",
    "找到 t > 33 時用 break 跳出迴圈",
    "答案是 index（從 0 開始數），不是溫度值",
]


def init(student_id):
    """初始化：輸入學號並嘗試連線追蹤系統"""
    global _student_id
    _student_id = str(student_id).strip()
    if not _student_id or _student_id == "在這裡輸入你的學號":
        print("⚠️ 請輸入你的學號！例如：week06.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(result):
    """Q1: 檢查 enumerate 編號清單"""
    if is_blocked():
        return
    label = "Q1 作物編號清單"
    _attempts["Q1"] += 1
    try:
        passed, status, got, expected = check_value(result, _Q1_HASH, str)
        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(result))
    except Exception as e:
        show_error(label, str(e))
        _results["Q1"] = False


def check_q2(total):
    """Q2: 檢查 zip 產量加總"""
    if is_blocked():
        return
    label = "Q2 作物總產量"
    _attempts["Q2"] += 1
    try:
        passed, status, got, expected = check_value(total, _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(total))
    except Exception as e:
        show_error(label, str(e))
        _results["Q2"] = False


def check_q3(found_pos):
    """Q3: 檢查 break 搜尋位置"""
    if is_blocked():
        return
    label = "Q3 高溫警報位置"
    _attempts["Q3"] += 1
    try:
        passed, status, got, expected = check_value(found_pos, _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(found_pos))
    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)
