import logging
import json
import os
import sqlite3
from aiogram import Router, F, Bot
from aiogram.types import CallbackQuery, Message, InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.fsm.context import FSMContext
from aiogram.filters import Command
import aiohttp

# Исправленный импорт
from .order_save import save_order
from db import get_user_language, get_language_text, get_button_text

logger = logging.getLogger(__name__)

router = Router(name="cryptobot")

# Загрузка API ключа из crypto_api.json
def load_cryptobot_token():
    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
        config_path = os.path.join(current_dir, 'crypto_api.json')
        print(f"Looking for config at: {config_path}")
        
        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
            token = config.get('cryptobot_token')
            print(f"Token loaded: {token[:10]}..." if token else "Token not found")
            return token
    except Exception as e:
        logger.error(f"Ошибка загрузки crypto_api.json: {e}")
        return None

# Загружаем токен при старте
CRYPTOBOT_TOKEN = load_cryptobot_token()
CRYPTOBOT_API_URL = "https://pay.crypt.bot/api"

print(f"CRYPTOBOT_TOKEN loaded: {CRYPTOBOT_TOKEN is not None}")

# Callback для проверки оплаты
CHECK_PAYMENT_CB = "check_payment_crypto"

async def create_cryptobot_invoice(amount: float, description: str = "Оплата товара") -> dict:
    """
    Создает инвойс в CryptoBot
    """
    if not CRYPTOBOT_TOKEN:
        logger.error("CryptoBot token not loaded")
        return None
        
    url = f"{CRYPTOBOT_API_URL}/createInvoice"
    
    headers = {
        "Crypto-Pay-API-Token": CRYPTOBOT_TOKEN,
        "Content-Type": "application/json"
    }
    
    data = {
        "asset": "USDT",
        "amount": str(amount),
        "description": description,
        "paid_btn_name": "viewItem",
        "paid_btn_url": "https://t.me/your_bot",
        "allow_comments": False,
        "allow_anonymous": False,
        "expires_in": 3600
    }
    
    print(f"Creating invoice for amount: {amount}")
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=headers, json=data) as response:
                result = await response.json()
                print(f"CryptoBot API response: {result}")
                if result.get("ok"):
                    return result.get("result")
                else:
                    logger.error(f"CryptoBot API error: {result}")
                    return None
    except Exception as e:
        logger.error(f"CryptoBot request error: {e}")
        return None

async def check_cryptobot_invoice(invoice_id: int) -> dict:
    """
    Проверяет статус инвойса в CryptoBot
    """
    if not CRYPTOBOT_TOKEN:
        logger.error("CryptoBot token not loaded")
        return None
        
    url = f"{CRYPTOBOT_API_URL}/getInvoices"
    
    headers = {
        "Crypto-Pay-API-Token": CRYPTOBOT_TOKEN
    }
    
    params = {
        "invoice_ids": str(invoice_id),
        "count": 1
    }
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers, params=params) as response:
                result = await response.json()
                print(f"Check invoice response: {result}")
                if result.get("ok") and result.get("result", {}).get("items"):
                    return result["result"]["items"][0]
                else:
                    return None
    except Exception as e:
        logger.error(f"CryptoBot check invoice error: {e}")
        return None

def build_payment_keyboard(lang: str, invoice_url: str) -> InlineKeyboardMarkup:
    """
    Создает клавиатуру с кнопками оплаты и проверки
    """
    # Текст кнопок из базы данных
    pay_button_text = get_button_text(lang, "button17", "💳 Оплатить")
    check_button_text = get_button_text(lang, "button15", "✅ Проверить оплату")
    
    keyboard = InlineKeyboardMarkup(
        inline_keyboard=[
            [InlineKeyboardButton(text=pay_button_text, url=invoice_url)],
            [InlineKeyboardButton(text=check_button_text, callback_data=CHECK_PAYMENT_CB)]
        ]
    )
    
    return keyboard

@router.callback_query(F.data == CHECK_PAYMENT_CB)
async def check_payment_callback(cb: CallbackQuery, state: FSMContext, bot: Bot):
    """
    Обработчик кнопки проверки оплаты (button15) - удаляет сообщение и показывает text15 при успешной оплате
    """
    user_id = cb.from_user.id
    lang = get_user_language(user_id)
    
    print(f"=== CHECK PAYMENT CALLBACK ===")
    print(f"User: {user_id}")
    
    # Получаем данные из состояния
    state_data = await state.get_data()
    invoice_id = state_data.get('cryptobot_invoice_id')
    payment_message_id = state_data.get('payment_message_id')
    
    print(f"Invoice ID from state: {invoice_id}")
    print(f"Payment message ID: {payment_message_id}")
    
    # Удаляем сообщение с оплатой
    try:
        if payment_message_id:
            await bot.delete_message(chat_id=cb.message.chat.id, message_id=payment_message_id)
            print(f"Deleted payment message: {payment_message_id}")
        else:
            await cb.message.delete()
            print("Deleted current message")
    except Exception as e:
        print(f"Error deleting payment message: {e}")
    
    if not invoice_id:
        # Если нет invoice_id в состоянии
        error_text = get_language_text(lang, "text16") or "Оплата не прошла"
        await cb.message.answer(error_text)
        print("No invoice ID in state - sending text16")
        return
    
    # Проверяем статус инвойса
    invoice_data = await check_cryptobot_invoice(invoice_id)
    
    if not invoice_data:
        error_text = get_language_text(lang, "text16") or "Оплата не прошла"
        await cb.message.answer(error_text)
        print("Invoice check failed - sending text16")
        return
    
    status = invoice_data.get('status', 'active')
    print(f"Invoice status: {status}")
    
    if status == 'paid':
        # Сохраняем заказ в базу данных через универсальную функцию
        order_saved = await save_order(state_data, user_id, "cryptobot", bot)
        if order_saved:
            print("Order successfully saved to database")
        else:
            print("Failed to save order to database")
        
        # Всегда показываем text15 при успешной оплате
        success_text = get_language_text(lang, "text15") or "Оплата прошла успешно!"
        await cb.message.answer(success_text)
        print("Payment successful - sending text15")
        # Очищаем состояние после успешной проверки
        await state.clear()
    else:
        error_text = get_language_text(lang, "text16") or "Оплата не прошла"
        await cb.message.answer(error_text)
        print(f"Payment not completed (status: {status}) - sending text16")

@router.message(Command("check"))
async def check_payment_command(message: Message, state: FSMContext):
    """
    Команда /check - проверяет статус оплаты
    """
    user_id = message.from_user.id
    lang = get_user_language(user_id)
    
    print(f"=== CHECK PAYMENT COMMAND ===")
    print(f"User: {user_id}")
    
    # Получаем данные из состояния
    state_data = await state.get_data()
    invoice_id = state_data.get('cryptobot_invoice_id')
    
    print(f"Invoice ID from state: {invoice_id}")
    
    if not invoice_id:
        # Если нет invoice_id в состоянии
        error_text = get_language_text(lang, "text16") or "Оплата не прошла"
        await message.answer(error_text)
        print("No invoice ID in state - sending text16")
        return
    
    # Проверяем статус инвойса
    invoice_data = await check_cryptobot_invoice(invoice_id)
    
    if not invoice_data:
        error_text = get_language_text(lang, "text16") or "Оплата не прошла"
        await message.answer(error_text)
        print("Invoice check failed - sending text16")
        return
    
    status = invoice_data.get('status', 'active')
    print(f"Invoice status: {status}")
    
    if status == 'paid':
        # Сохраняем заказ в базу данных через универсальную функцию
        order_saved = await save_order(state_data, user_id, "cryptobot", message.bot)
        if order_saved:
            print("Order successfully saved to database")
        else:
            print("Failed to save order to database")
        
        # Всегда показываем text15 при успешной оплате
        success_text = get_language_text(lang, "text15") or "Оплата прошла успешно!"
        await message.answer(success_text)
        print("Payment successful - sending text15")
        # Очищаем состояние после успешной проверки
        await state.clear()
    else:
        error_text = get_language_text(lang, "text16") or "Оплата не прошла"
        await message.answer(error_text)
        print(f"Payment not completed (status: {status}) - sending text16")