"""Week 3: 字串進階操作與格式化"""

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

# --- 答案 hash ---
# Q1: "  Tomato  ".strip().lower() => "tomato"
_Q1_HASH = "5ed728c2fa5d767bc6c1ec6a732db1e37c343be46913e6498d340f7782691f14"
# Q2: f"溫室A：溫度 {28.567:.1f}°C，濕度 {72.3:.0f}%" => "溫室A：溫度 28.6°C，濕度 72%"
_Q2_HASH = "d32036061a2e08677f57771efd647026ea3a05d382fc69c4a2fda50d18cd48a0"
# Q3: int("Tomato,150,GH-A,2024-03-15".split(",")[1]) => 150
_Q3_HASH = "9ae2bdd7beedc2e766c6b76585530e16925115707dc7a06ab5ee4aa2776b2c7b"

# --- 提示 ---
_Q1_HINTS = [
    "strip() 可以去除前後空白",
    "lower() 可以把字串轉成小寫",
    '試試：crop_name.strip().lower()',
]
_Q2_HINTS = [
    "f-string 格式：f\"{變數:.1f}\" 可以控制小數位數",
    ":.0f 會四捨五入到整數（不顯示小數點）",
    '完整格式：f"{gh_name}：溫度 {temp:.1f}°C，濕度 {humidity:.0f}%"',
]
_Q3_HINTS = [
    'split(",") 可以用逗號把字串切開成 list',
    "parts[1] 取第二個元素（index 從 0 開始）",
    "記得用 int() 把字串轉成整數",
]


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


def check_q2(report):
    """Q2: 檢查溫室環境報告字串"""
    if is_blocked():
        return
    label = "Q2 溫室環境報告"
    _attempts["Q2"] += 1
    try:
        passed, status, got, expected = check_value(report, _Q2_HASH, str)
        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(report))
    except Exception as e:
        show_error(label, str(e))
        _results["Q2"] = False


def check_q3(yield_amount):
    """Q3: 檢查從 CSV 解析出的產量"""
    if is_blocked():
        return
    label = "Q3 農產品資料解析"
    _attempts["Q3"] += 1
    try:
        passed, status, got, expected = check_value(yield_amount, _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(yield_amount))
    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)
