import json
from aiogram import Bot, Dispatcher, F
from aiogram.types import Message, ReplyKeyboardMarkup, KeyboardButton
from aiogram.enums import ParseMode
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.context import FSMContext
from aiogram.types import ReplyKeyboardRemove
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import BotCommand
from aiogram.utils.keyboard import ReplyKeyboardBuilder
from aiogram import Router
from aiogram import html
import asyncio
import logging

#from aiogram import asyncio

#API_TOKEN = "YOUR_BOT_TOKEN"
# импорты
from config_reader import config

# Включаем логирование, чтобы не пропустить важные сообщения
logging.basicConfig(level=logging.INFO)

# --- State Machine ---
class FeedbackForm(StatesGroup):
    name = State()
    contact = State()
    wants_reply = State()
    message = State()

# --- Router ---
router = Router()

data_store = []

@router.message(F.text == "/hello")
async def cmd_hello(message: Message):
    await message.answer(
        f"Hello, {html.bold(html.quote(message.from_user.full_name))}",
        parse_mode=ParseMode.HTML
    )
@router.message(F.text == "/start")
async def cmd_start(message: Message, state: FSMContext):
    await state.set_state(FeedbackForm.name)
    await message.answer("👋 Welcome! Please enter your full name:")

@router.message(FeedbackForm.name)
async def process_name(message: Message, state: FSMContext):
    await state.update_data(name=message.text)
    await state.set_state(FeedbackForm.contact)
    await message.answer("📞 Please provide your email or phone number:")

@router.message(FeedbackForm.contact)
async def process_contact(message: Message, state: FSMContext):
    await state.update_data(contact=message.text)
    keyboard = ReplyKeyboardMarkup(keyboard=[
        [KeyboardButton(text="Yes")],
        [KeyboardButton(text="No")]
    ], resize_keyboard=True, one_time_keyboard=True)
    await state.set_state(FeedbackForm.wants_reply)
    await message.answer("✅ Do you want a reply?", reply_markup=keyboard)

@router.message(FeedbackForm.wants_reply)
async def process_wants_reply(message: Message, state: FSMContext):
    reply = message.text.lower() == "yes"
    await state.update_data(wants_reply=reply)
    await state.set_state(FeedbackForm.message)
    await message.answer("✍️ Please type your message:", reply_markup=ReplyKeyboardRemove())

@router.message(FeedbackForm.message)
async def process_message(message: Message, state: FSMContext):
    user_data = await state.update_data(message=message.text)

    record = {
        "telegram_username": message.from_user.full_name,
        "name": user_data["name"],
        "contact": user_data["contact"],
        "wants_reply": user_data["wants_reply"],
        "message": user_data["message"]
    }

    data_store.append(record)

    # Save to JSON
    with open("submissions.json", "w") as f:
        json.dump(data_store, f, indent=2)

    await message.answer("✅ Thank you! We've received your message.")
    await state.clear()

@router.message(F.text == "/cancel")
async def cancel(message: Message, state: FSMContext):
    await state.clear()
    await message.answer("❌ Your submission was cancelled.")

# --- Main ---
async def main():
    #bot = Bot(token=API_TOKEN, parse_mode=ParseMode.HTML)
    bot = Bot(token=config.bot_token.get_secret_value())
    dp = Dispatcher(storage=MemoryStorage())
    dp.include_router(router)

    # Optional: set commands for user
    await bot.set_my_commands([
        BotCommand(command="start", description="Start feedback submission")
    ])

    await dp.start_polling(bot)

if __name__ == "__main__":
    #import asyncio
    asyncio.run(main())