from nonebot import get_plugin_config, on_command
from nonebot.plugin import PluginMetadata
from nonebot.rule import to_me
from nonebot.adapters.onebot.v11 import Message,MessageEvent
from nonebot.params import ArgPlainText,CommandArg
from .config import Config
from nonebot.typing import T_State
from .AccountSpider import AccountSpider
from nonebot_plugin_saa import Text, Image, MessageFactory
import os
import random
import asyncio

__plugin_meta__ = PluginMetadata(
    name="大漠余额查询",
    description="查询大漠插件平台账户余额的插件",
    usage="""
    指令：
    - 大漠余额
    - 余额查询
    
    权限：
    仅限指定用户（QQ：1424473282）使用
    
    使用流程：
    1. 发送"大漠余额"或"余额查询"指令
    2. 机器人会返回验证码图片
    3. 输入验证码完成查询
    """,
    config=Config,
)

config = get_plugin_config(Config)


# 指令：大漠余额
check_balance = on_command("大漠余额", aliases={"余额查询"}, priority=5,block=True)

@check_balance.handle()
async def handle_first_receive(event: MessageEvent, state: T_State):
    user_id = event.user_id
    if user_id not in [1424473282]:
        await asyncio.sleep(random.uniform(2, 3))
        await check_balance.finish("你没有权限进行此操作")

    try:
        spider = AccountSpider(save_dir=os.path.dirname(__file__))
        state["spider"] = spider
        # 获取验证码
        image_bytes = spider.get_verification_code()
        await asyncio.sleep(random.uniform(2, 3))
        await MessageFactory([Text("请发送验证码图片中的内容进行验证："), Image(image_bytes)]).send()
    except Exception as e:
        logger.error(f"获取验证码失败: {e}")
        await check_balance.finish("获取验证码失败，请稍后再试")

# 验证用户输入的验证码
@check_balance.got("captcha", prompt="请输入验证码：")
async def handle_captcha(event: MessageEvent, state: T_State, captcha: str = ArgPlainText("captcha")):
    user_id = event.user_id
    if user_id not in [1424473282]:
        await asyncio.sleep(random.uniform(2, 3))
        await check_balance.finish("你没有权限进行此操作")

    USERNAME = os.environ.get("DAMO_USERNAME", "")
    PASSWORD = os.environ.get("DAMO_PASSWORD", "")
    if not USERNAME or not PASSWORD:
        await check_balance.finish("大漠账号未配置，请设置环境变量")

    spider = state.get("spider")
    if not spider:
        await check_balance.finish('会话异常，请重新发送"大漠余额"')

    try:
        if spider.login(USERNAME, PASSWORD, captcha):
            balance = spider.get_balance()
            await asyncio.sleep(random.uniform(2, 3))
            await check_balance.finish(f"大漠账户余额：{balance}元")
        else:
            await asyncio.sleep(random.uniform(2, 3))
            await check_balance.reject("登录失败，请检查验证码是否正确")
    except Exception as e:
        logger.error(f"查询余额失败: {e}")
        await check_balance.finish("查询余额失败，请稍后再试")
