"""Week 8: 串列深入探討 — 建立、索引、切片、方法、排序"""

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

# --- 答案 hash ---
# Q1: inventory after ops → inventory[1] = "玉米"
_Q1_HASH = "dfa4670a83c67131626d754c860231e8d57cc594558b33af871e7e0f81d3edea"
# Q2: hot_count from first_five [32,28,35,27,30] → 2 (32,35 > 30)
_Q2_HASH = "d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35"
# Q3: median of sorted [600,850,950,1100,1200] → 950
_Q3_HASH = "5538e771949ffec150f6e8260b2e3801236c7373ed62c22a3f82dc0071265cc4"

# --- 提示 ---
_Q1_HINTS = [
    "追蹤每一步操作後 list 的狀態",
    "append 加在最後、insert(1,...) 在 index 1 插入、remove 刪除第一個符合的",
    "操作順序：[] → append 番茄 → append 小黃瓜 → append 草莓 → insert(1,玉米) → remove 小黃瓜",
]
_Q2_HINTS = [
    "temps[:5] 取出前五個溫度",
    "用 for 迴圈逐一檢查 > 30 的溫度",
    "前五個是 [32, 28, 35, 27, 30]，其中 32 和 35 > 30",
]
_Q3_HINTS = [
    "sorted() 會回傳排序好的新 list",
    "中位數是排序後最中間的元素",
    "sorted 後 index 為 len//2 的元素就是中位數",
]


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


def check_q2(hot_count):
    """Q2: 檢查高溫天數"""
    if is_blocked():
        return
    label = "Q2 高溫天數統計"
    _attempts["Q2"] += 1
    try:
        passed, status, got, expected = check_value(hot_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(hot_count))
    except Exception as e:
        show_error(label, str(e))
        _results["Q2"] = False


def check_q3(median):
    """Q3: 檢查中位數"""
    if is_blocked():
        return
    label = "Q3 產量中位數"
    _attempts["Q3"] += 1
    try:
        passed, status, got, expected = check_value(median, _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(median))
    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)
