"""Week 2: 變數、資料型態與基本運算"""

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

# --- 答案 hash ---
_Q1_HASH = "c746ee2edf45fa00fca8d08045b2575aac17cf3eeb3f2b0da5e5301fae8d1e47"
_Q2_HASH = "18ffa98efe1ee61f9f0d9714e0cb559fcb8354c32d4654e3e9b438587111a9f7"
_Q3A_HASH = "8f1bc303eb0c11cbe5cf30b7d439f4bc36f03fd35f1492a02ebdb6e534419151"
_Q3B_HASH = "3cbc87c7681f34db4617feaa2c8801931bc5e42d8d0f560e756dd4cd92885f18"

# --- 提示 ---
_Q1_HINTS = [
    "想想 13500 ÷ 3 是多少",
    "注意：/ 會得到 float，題目要求 int，試試 //",
]
_Q2_HINTS = [
    "先把七天的溫度加起來，再除以 7",
    "記得用 round() 四捨五入到小數點後一位：round(數值, 1)",
]
_Q3A_HINTS = [
    "f-string 的格式是 f\"...{變數}...\"",
    '字串格式：f"{farm_name}的面積是{area_hectares}公頃"',
]
_Q3B_HINTS = [
    "比較運算子 > 會回傳 True 或 False",
    "area_hectares > 50 的結果就是布林值",
]


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


def check_q2(avg_temp):
    """Q2: 檢查平均溫度"""
    if is_blocked():
        return
    label = "Q2 平均溫度"
    _attempts["Q2"] += 1
    try:
        passed, status, got, expected = check_value(avg_temp, _Q2_HASH, float)
        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(avg_temp))
    except Exception as e:
        show_error(label, str(e))
        _results["Q2"] = False


def check_q3(farm_info, is_large_farm):
    """Q3: 檢查農場資訊字串與布林判斷"""
    if is_blocked():
        return
    label_a = "Q3a 農場資訊字串"
    label_b = "Q3b 大型農場判斷"

    # --- Q3a: 字串 ---
    _attempts["Q3a"] += 1
    try:
        passed_a, status, got, expected = check_value(farm_info, _Q3A_HASH, str)
        if passed_a:
            show_pass(label_a)
            _results["Q3a"] = True
        elif status == "type_error":
            show_type_error(label_a, got, expected)
            _results["Q3a"] = False
        else:
            show_fail(label_a, "字串內容不正確", _Q3A_HINTS, _attempts["Q3a"])
            _results["Q3a"] = False
        log_attempt(_student_id, _WEEK, "Q3a", _results.get("Q3a", False),
                    submitted_code=repr(farm_info))
    except Exception as e:
        show_error(label_a, str(e))
        _results["Q3a"] = False

    # --- Q3b: 布林 ---
    _attempts["Q3b"] += 1
    try:
        passed_b, status, got, expected = check_value(is_large_farm, _Q3B_HASH, bool)
        if passed_b:
            show_pass(label_b)
            _results["Q3b"] = True
        elif status == "type_error":
            show_type_error(label_b, got, expected)
            _results["Q3b"] = False
        else:
            show_fail(label_b, "布林值不正確", _Q3B_HINTS, _attempts["Q3b"])
            _results["Q3b"] = False
        log_attempt(_student_id, _WEEK, "Q3b", _results.get("Q3b", False),
                    submitted_code=repr(is_large_farm))
    except Exception as e:
        show_error(label_b, str(e))
        _results["Q3b"] = False


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