from aiogram import Bot, Dispatcher, types
from aiogram.utils import executor
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup,CallbackQuery
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup

from utils.fmt_maintain_params import fmt_maintain_params,fmt_type
from openai_config.openai_utils import ask
from api.api import call_maintain_api

import sys
import os
import pandas as pd
import logging
import uuid


bot = Bot(token="7542850818:AAEvT7wQOTRmJm5m_3Td3CS_GLcR0nPdY6Q")
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)

logging.basicConfig(level=logging.INFO)

GROUP_ID = -4660405221 #群組id

pending_confirmations = {}

class Form(StatesGroup):
    waiting_for_confirm = State()


class StopMaintenance(StatesGroup):
    waiting_for_platform_name = State()
    waiting_for_platform_name_test = State()


@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
    await message.reply("Hello! I'm a bot!")

@dp.message_handler(content_types=types.ContentType.TEXT)
async def handle_group_text(message: types.Message,):
    chat_type = message.chat.type
    print(message.text)
    if chat_type in ['group', 'supergroup']:
        response = ask(query=message.text)

        type = fmt_type(response)    

        if(type["type"] == "維護訊息"):
            fmt_data = fmt_maintain_params(response)

            uid = str(uuid.uuid4())
            pending_confirmations[uid] = fmt_data
            keyboard = InlineKeyboardMarkup(row_width=1)  # 兩顆一排
            keyboard.add(
                InlineKeyboardButton("✅✅ 開啟我方“正式”平台維護", callback_data=f"confirm|{uid}|正式"),
                InlineKeyboardButton("✅ 開啟我方“測試”平台維護", callback_data=f"confirm|{uid}|測試"),
                InlineKeyboardButton("❌ 取消指令", callback_data=f"cancel|{uid}")
            )

            
            await bot.send_message(chat_id=GROUP_ID,text=response,reply_markup=keyboard)
        elif(message.text == "/stop" or message.text == "/stop@wsky_maintain_bot"):
            await handle_stop(message)
        elif(message.text == "/stop_test" or message.text == "/stop_test@wsky_maintain_bot"):
            await handle_stop_test(message)
        else:
            return
        
    else:
        if(message.text == "/stop" or message.text == "/stop@wsky_maintain_bot"):
            await handle_stop(message)
        elif(message.text == "/stop_test" or message.text == "/stop_test@wsky_maintain_bot"):
            await handle_stop_test(message)
        else:
            await message.reply("我不提供私訊功能 📨")

@dp.callback_query_handler(lambda c: c.data.startswith("confirm|"))
async def handle_confirm(callback_query: types.CallbackQuery):
    await callback_query.answer("✅ 維護流程已確認")

    
    uid = callback_query.data.split("|")[1]
    fmt_data = pending_confirmations.get(uid)

    is_test = callback_query.data.split("|")[2] == "測試"

    await call_maintain_api(
        maintain_platform=["911機台測試站","飛龍測試站","魔方測試站","馬上發測試站","馬上發測試站VN"] if is_test else ["911機台正式站","飛龍正式站","魔方正式站","馬上發正式站","馬上發正式站VN"],
        fmt_data=fmt_data,
        bot=callback_query.message
    )
    if not fmt_data:
        await bot.send_message(callback_query.message.chat.id, "⚠️ 無效或過期的資料")
        return
    
    # 移除按鈕
    await bot.edit_message_reply_markup(
        chat_id=callback_query.message.chat.id,
        message_id=callback_query.message.message_id,
        reply_markup=None
    )
    
    await bot.send_message(callback_query.message.chat.id,"完成指令")



@dp.callback_query_handler(lambda c: c.data.startswith("cancel|"))
async def handle_cancel(callback_query: types.CallbackQuery):
    await callback_query.answer("❌ 已取消")

    await bot.edit_message_reply_markup(
        chat_id=callback_query.message.chat.id,
        message_id=callback_query.message.message_id,
        reply_markup=None
    )


    await bot.send_message(callback_query.message.chat.id, "❌ 指令已取消")


@dp.message_handler(commands=['stop'], commands_prefix="/")
async def handle_stop(message: types.Message,is_test=False):
    await message.reply("請輸入欲取消維護的“”“正式”“”平台名稱")
    await StopMaintenance.waiting_for_platform_name.set()
 
@dp.message_handler(commands=['stop_test'], commands_prefix="/")
async def handle_stop_test(message: types.Message,is_test=False):
    await message.reply("請輸入欲取消維護的“”“測試站”“”平台名稱")
    await StopMaintenance.waiting_for_platform_name_test.set()


@dp.message_handler(state=StopMaintenance.waiting_for_platform_name)
async def handle_platform_name(message: types.Message, state: FSMContext):
    platform_name = message.text.strip()
 
    await call_maintain_api(
        # maintain_platform=["911機台測試站","飛龍測試站","魔方測試站","911機台正式站","飛龍正式站","魔方正式站"],
        maintain_platform=["911機台正式站","飛龍正式站","魔方正式站","馬上發正式站","馬上發正式站VN"],

        fmt_data={
        "platform": platform_name.upper(),
        "s_date": "",
        "s_time": "",
        "e_date": "",
        "e_time": ""
        },
        cancel_maintain=True,
        bot=message
    )

    await message.reply(f"✅ 已成功取消 {platform_name} 的維護！")

    await state.finish()

@dp.message_handler(state=StopMaintenance.waiting_for_platform_name_test)
async def handle_platform_name_test(message: types.Message, state: FSMContext):
    platform_name = message.text.strip()
 
    await call_maintain_api(
        maintain_platform=["911機台測試站","飛龍測試站","魔方測試站","馬上發測試站","馬上發測試站VN"],

        fmt_data={
        "platform": platform_name.upper(),
        "s_date": "",
        "s_time": "",
        "e_date": "",
        "e_time": ""
        },
        cancel_maintain=True,
        bot=message
    )

    await message.reply(f"✅ 已成功取消 {platform_name} 的維護！")

    await state.finish()


async def set_commands(bot: Bot):
    commands = [
        types.BotCommand(command="/stop", description="取消“正式正式正式”平台維護"),
        types.BotCommand(command="/stop_test", description="取消“正式正式正式”平台維護"),
    ]
    await bot.set_my_commands(commands)

async def on_startup(dp: Dispatcher):
    await set_commands(dp.bot) 

def init_bot_aiogram():
    print("Bot is running")

    executor.start_polling(dp, skip_updates=True, on_startup=on_startup)