from Linebot_handler import Captcha_state
from Linebot_handler.Expense import (
    EXPENSE_TEMPLATE,
    save_expense,
    delete_expense,
    query_today,
    query_month,
    parse_multiline_expense,
)


def handle_text(line_user_id: str, text: str) -> str:
    if text == "查今天":
        return query_today(line_user_id)
    if text == "查本月":
        return query_month(line_user_id)
    if text in ("記帳", "記帳說明"):
        return EXPENSE_TEMPLATE
    if text.startswith("刪除 "):
        return delete_expense(line_user_id, text[3:].strip())

    # 多行記帳
    if "\n" in text:
        fields = parse_multiline_expense(text)
        if fields:
            return save_expense(line_user_id, fields)
        return (
            "格式不正確 😅\n\n"
            "必填欄位：品項、類別、金額\n"
            "點下方「記帳」取得模板！"
        )

    return (
        "點下方「記帳」取得記帳模板\n"
        "或輸入「查今天」/「查本月」查詢"
    )


def handle_captcha(text: str) -> bool:
    """回傳 True 表示是驗證碼輸入"""
    if (
        text.isdigit()
        and len(text) == 5
        and Captcha_state.captcha_event
        and not Captcha_state.captcha_event.is_set()
    ):
        Captcha_state.captcha_answer = text
        Captcha_state.captcha_event.set()
        return True
    return False