"""Week 4: 條件判斷與決策邏輯"""

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

# --- 測試案例 ---
_Q1_CASES = [
    {"args": (38,), "expected_hash": "75913f3314a996d64450ba5b38e07c5e6ffdc74b80c8b0e007b9d43e28546f74"},
    {"args": (25,), "expected_hash": "e27f57048df3a7ea9ca3313d04c7814b6cedcae137e24242207135c410a6abf8"},
    {"args": (15,), "expected_hash": "0f223e54d5c544672804cb59ac152fcf21e500440c3f54e9025c2069f9b7f9ab"},
    {"args": (20,), "expected_hash": "e27f57048df3a7ea9ca3313d04c7814b6cedcae137e24242207135c410a6abf8"},
    {"args": (35.1,), "expected_hash": "75913f3314a996d64450ba5b38e07c5e6ffdc74b80c8b0e007b9d43e28546f74"},
]
_Q2_CASES = [
    {"args": (30, False), "expected_hash": "3cbc87c7681f34db4617feaa2c8801931bc5e42d8d0f560e756dd4cd92885f18"},
    {"args": (50, False), "expected_hash": "60a33e6cf5151f2d52eddae9685cfa270426aa89d8dbc7dfb854606f1d1a40fe"},
    {"args": (30, True), "expected_hash": "60a33e6cf5151f2d52eddae9685cfa270426aa89d8dbc7dfb854606f1d1a40fe"},
    {"args": (50, True), "expected_hash": "60a33e6cf5151f2d52eddae9685cfa270426aa89d8dbc7dfb854606f1d1a40fe"},
    {"args": (40, False), "expected_hash": "60a33e6cf5151f2d52eddae9685cfa270426aa89d8dbc7dfb854606f1d1a40fe"},
]
_Q3_CASES = [
    {"args": (3,), "expected_hash": "e47c488a2ab3b43a2efd37694c853ebc2e50a55f38f890ee55223e672a2d3278"},
    {"args": (7,), "expected_hash": "0b76aa2db29bff74220bd043a2a4b09bb08bdba9e3ce36f33691b65505b09dd7"},
    {"args": (45,), "expected_hash": "7ac0e587eddc38009eea9e95a937b510174ce951fefebff00223aa2ec8561d04"},
    {"args": (75,), "expected_hash": "32a928f9192c492ccaa0934e6854295ea1c0e907f476927e7d450bd707a0e39c"},
    {"args": (100,), "expected_hash": "8918dc100e7fbe0933ac4b6bdfb9fdbe250fb86c083a026659e72977e13626b4"},
    {"args": (0,), "expected_hash": "e47c488a2ab3b43a2efd37694c853ebc2e50a55f38f890ee55223e672a2d3278"},
    {"args": (60,), "expected_hash": "32a928f9192c492ccaa0934e6854295ea1c0e907f476927e7d450bd707a0e39c"},
]

# --- 提示 ---
_Q1_HINTS = [
    "用 if/elif/else 判斷溫度範圍",
    "temp > 35 → '過高'，temp >= 20 → '適中'，否則 → '過低'",
    "注意邊界值：20 度算「適中」，35 度也算「適中」",
]
_Q2_HINTS = [
    "需要同時滿足兩個條件：濕度低 且 沒下雨",
    "用 and 連接兩個條件：soil_moisture < 40 and not is_raining",
    "記得 return True 或 False",
]
_Q3_HINTS = [
    "用 if/elif/else 判斷天數範圍",
    "注意邊界：7 天不算「發芽期」，要算「幼苗期」",
    "順序：< 7 發芽、< 21 幼苗、< 60 營養生長、< 90 開花、其他結果",
]


def init(student_id):
    """初始化：輸入學號並嘗試連線追蹤系統"""
    global _student_id
    _student_id = str(student_id).strip()
    if not _student_id or _student_id == "在這裡輸入你的學號":
        print("⚠️ 請輸入你的學號！例如：week04.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)
