"""Week 7: 函數基礎 — def, 參數, return, docstring, scope"""

from checker._core import check_function
from checker._feedback import (
    show_pass, show_function_result, show_summary, show_error,
)
from checker._tracking import init_tracking, log_attempt, is_blocked, _capture_source

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

# --- 測試案例 ---
_Q1_CASES = [
    {"args": (20,), "expected_hash": "d0d163dd0cf677f765af75266e85761f8189acff4cc2c6ca51eedcb78695c3a3"},   # "乾燥"
    {"args": (30,), "expected_hash": "e27f57048df3a7ea9ca3313d04c7814b6cedcae137e24242207135c410a6abf8"},   # "適中"
    {"args": (50,), "expected_hash": "e27f57048df3a7ea9ca3313d04c7814b6cedcae137e24242207135c410a6abf8"},   # "適中"
    {"args": (70,), "expected_hash": "e27f57048df3a7ea9ca3313d04c7814b6cedcae137e24242207135c410a6abf8"},   # "適中"
    {"args": (80,), "expected_hash": "3d1557f2f46d62ad39b77928d6cbc0cf6cb1e75936e80424369a8af876bd05c0"},   # "潮濕"
    {"args": (29,), "expected_hash": "d0d163dd0cf677f765af75266e85761f8189acff4cc2c6ca51eedcb78695c3a3"},   # "乾燥"
    {"args": (71,), "expected_hash": "3d1557f2f46d62ad39b77928d6cbc0cf6cb1e75936e80424369a8af876bd05c0"},   # "潮濕"
]

_Q2_CASES = [
    {"args": (2, "稻米"), "expected": 240},
    {"args": (3, "玉米"), "expected": 450},
    {"args": (1, "大豆"), "expected": 100},
    {"args": (5, "稻米"), "expected": 600},
]

_Q3_CASES = [
    {"args": ([28, 32, 27, 35, 30],), "expected": (27, 35, 30.4)},
    {"args": ([20, 25, 30],), "expected": (20, 30, 25.0)},
    {"args": ([15],), "expected": (15, 15, 15.0)},
]

# --- 提示 ---
_Q1_HINTS = [
    "用 if/elif/else 判斷：< 30 乾燥、30-70 適中、> 70 潮濕",
    "注意邊界：30 和 70 都算「適中」",
    "記得用 return 回傳字串",
]
_Q2_HINTS = [
    "稻米每公頃 120 kg、玉米 150 kg、其他 100 kg",
    "根據 crop_type 決定每公頃用量，乘以面積",
    "回傳 int：用 int(area * rate) 確保是整數",
]
_Q3_HINTS = [
    "用迴圈找最小值和最大值（不能用 min/max）",
    "平均值 = 總和 / 個數，用 round(avg, 1) 四捨五入",
    "回傳 tuple：return (min_val, max_val, avg_val)",
]


def init(student_id):
    """初始化：輸入學號並嘗試連線追蹤系統"""
    global _student_id
    _student_id = str(student_id).strip()
    if not _student_id or _student_id == "在這裡輸入你的學號":
        print("⚠️ 請輸入你的學號！例如：week07.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(fn):
    """Q1: 檢查土壤濕度分類函數"""
    if is_blocked():
        return
    label = "Q1 土壤濕度分類"
    _attempts["Q1"] += 1
    try:
        all_passed, case_results = check_function(fn, _Q1_CASES)
        if all_passed:
            show_pass(label)
            _results["Q1"] = True
        else:
            show_function_result(label, False, case_results, _Q1_HINTS, _attempts["Q1"])
            _results["Q1"] = False
        log_attempt(_student_id, _WEEK, "Q1", _results.get("Q1", False),
                    submitted_code=_capture_source(fn))
    except Exception as e:
        show_error(label, str(e))
        _results["Q1"] = False


def check_q2(fn):
    """Q2: 檢查施肥量計算函數"""
    if is_blocked():
        return
    label = "Q2 施肥量計算"
    _attempts["Q2"] += 1
    try:
        all_passed, case_results = check_function(fn, _Q2_CASES)
        if all_passed:
            show_pass(label)
            _results["Q2"] = True
        else:
            show_function_result(label, False, case_results, _Q2_HINTS, _attempts["Q2"])
            _results["Q2"] = False
        log_attempt(_student_id, _WEEK, "Q2", _results.get("Q2", False),
                    submitted_code=_capture_source(fn))
    except Exception as e:
        show_error(label, str(e))
        _results["Q2"] = False


def check_q3(fn):
    """Q3: 檢查溫度統計函數"""
    if is_blocked():
        return
    label = "Q3 溫度統計"
    _attempts["Q3"] += 1
    try:
        all_passed, case_results = check_function(fn, _Q3_CASES)
        if all_passed:
            show_pass(label)
            _results["Q3"] = True
        else:
            show_function_result(label, False, case_results, _Q3_HINTS, _attempts["Q3"])
            _results["Q3"] = False
        log_attempt(_student_id, _WEEK, "Q3", _results.get("Q3", False),
                    submitted_code=_capture_source(fn))
    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)
