from fastapi import APIRouter, Request, HTTPException
from linebot.v3 import WebhookHandler
from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
    ReplyMessageRequest,
    TextMessage,
)
from linebot.v3.webhooks import MessageEvent, TextMessageContent, FollowEvent
from linebot.v3.exceptions import InvalidSignatureError
from config import LINE_CHANNEL_ACCESS_TOKEN, LINE_CHANNEL_SECRET
from Linebot_handler.Handlers import handle_text, handle_captcha

router = APIRouter()
configuration = Configuration(access_token=LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)


@router.post("/webhook")
async def webhook(request: Request):
    signature = request.headers.get("X-Line-Signature", "")
    body = await request.body()
    try:
        handler.handle(body.decode(), signature)
    except InvalidSignatureError:
        raise HTTPException(status_code=400, detail="Invalid signature")
    return "OK"


def _reply(reply_token: str, text: str):
    with ApiClient(configuration) as api_client:
        MessagingApi(api_client).reply_message(
            ReplyMessageRequest(
                reply_token=reply_token,
                messages=[TextMessage(text=text)]
            )
        )


@handler.add(MessageEvent, message=TextMessageContent)
def on_message(event):
    line_user_id = event.source.user_id
    msg = event.message.text.strip()

    if handle_captcha(msg):
        _reply(event.reply_token, "✅ 驗證碼已送出！")
    else:
        _reply(event.reply_token, handle_text(line_user_id, msg))


@handler.add(FollowEvent)
def on_follow(event):
    _reply(event.reply_token, (
        "👋 歡迎使用 Myfinance 記帳 Bot！\n\n"
        "📝 點下方「記帳」開始記帳\n"
        "📊 點「查今天」或「查本月」查詢\n\n"
        "開始記帳吧！💪"
    ))