# bot/handlers/sms.py

import asyncio
import logging
import time
import json
from pathlib import Path
from typing import Optional, List, Tuple
from aiogram import Dispatcher, types, F
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup

from ..data import get_user_api_key, get_user_operator, get_user_country
from ..api import SmsHubAPI
from ..utils import get_usd_to_rub_rate, safe_edit_or_send_message
from .start import send_main_menu
from .activation import user_activations, poll_for_sms
from ..constants.operators import OPERATOR_DISPLAY_NAMES
from ..constants.countries import COUNTRIES
from ..constants.services import SERVICE_DISPLAY_NAMES

logger = logging.getLogger(__name__)

class SmsOrderState(StatesGroup):
    waiting_for_service = State()
    waiting_for_max_price = State()

SERVICES: List[Tuple[str, str]] = list(SERVICE_DISPLAY_NAMES.items())
POPULARITY_FILE = Path("service_popularity.json")

def load_popularity_data() -> dict:
    if POPULARITY_FILE.exists():
        with open(POPULARITY_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {}

def save_popularity_data(popularity_data: dict):
    with open(POPULARITY_FILE, 'w', encoding='utf-8') as f:
        json.dump(popularity_data, f, ensure_ascii=False, indent=4)

def update_service_popularity(service_code: str):
    popularity_data = load_popularity_data()
    if service_code in popularity_data:
        popularity_data[service_code] += 1
    else:
        popularity_data[service_code] = 1
    save_popularity_data(popularity_data)

def get_sorted_services(available_services: List[str]) -> List[Tuple[str, str]]:
    popularity_data = load_popularity_data()
    sorted_services = sorted(
        [(code, name) for code, name in SERVICES if code in available_services],
        key=lambda service: popularity_data.get(service[0], 0),
        reverse=True
    )
    return sorted_services

def get_service_pages(services: List[Tuple[str, str]], page_size: int = 18) -> List[List[Tuple[str, str]]]:
    pages = []
    for i in range(0, len(services), page_size):
        pages.append(services[i:i + page_size])
    return pages

def build_service_keyboard(page_number: int, available_services: List[str], services_with_numbers: set) -> InlineKeyboardBuilder:
    sorted_services = get_sorted_services(available_services)
    services_pages = get_service_pages(sorted_services)
    keyboard = InlineKeyboardBuilder()

    if page_number < len(services_pages):
        current_page = services_pages[page_number]

        for code, name in current_page:
            # Append a red circle emoji if the service does not have available numbers
            if code not in services_with_numbers:
                name += " 🔴"
            keyboard.button(text=name, callback_data=f"service_select:{code}")

        keyboard.adjust(3)
        
        if len(services_pages) > 1:  # Only show navigation buttons if more than one page exists
            nav_buttons = []
            if page_number > 0:
                nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"service_page:{page_number - 1}"))
            # Centralize page number information
            nav_buttons.append(types.InlineKeyboardButton(text=f"Страница {page_number + 1}/{len(services_pages)}", callback_data="ignore"))
            if page_number < len(services_pages) - 1:
                nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"service_page:{page_number + 1}"))
            keyboard.row(*nav_buttons)
        
        keyboard.row(types.InlineKeyboardButton(text="🔙 Назад в меню", callback_data="back_to_main_menu"))
    
    return keyboard

def get_service_message_text(total_services_with_numbers: int, total_services_for_country: int, services_with_operator: int, country_name: str, operator_name: str) -> str:
    return (
        f"🔢 *Общее кол-во сервисов:* `{total_services_for_country}`\n"
        f"💼 *Доступные сервисы (где есть номера):* `{total_services_with_numbers}`\n"
        f"✅ *Доступные сервисы (с вашими настройками оператора):* `{services_with_operator}`\n\n"
        f"— Нажмите на кнопку, чтобы выбрать сервис.\n"
        f"— Или введите название, чтобы найти сервис.\n\n"
        f"🐾 *Текущая страна:* `{country_name}`\n"
        f"📡 *Текущий оператор:* `{operator_name}`\n"
        f"_(Эти параметры можно изменить в настройках)_\n"
        f"\n_🔴 - нет номеров_"
    )

async def fetch_all_services(user_api_key: str, user_country_code: str, state: FSMContext) -> Tuple[Optional[List[str]], int, int]:
    smshub_api = SmsHubAPI(user_api_key)
    max_attempts = 3
    last_exception = None
    available_services = []
    services_with_numbers = set()

    for attempt in range(1, max_attempts + 1):
        try:
            numbers_status = await smshub_api.get_numbers_status(country=user_country_code)
            if numbers_status:
                # Все сервисы и сервисы с доступными номерами
                available_services = [service.split('_')[0] for service in numbers_status.keys()]
                services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}
                break
        except Exception as e:
            last_exception = e
            logger.error(f"Ошибка при запросе статуса всех сервисов, попытка {attempt}: {e}")

        data = await state.get_data()
        if data.get("cancel_request"):
            logger.info("Запрос на получение всех сервисов был отменен.")
            return None, 0, 0

        progress_text = f"Попытка {attempt}/{max_attempts} получения списка всех сервисов..."
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
        keyboard.adjust(1)

        await safe_edit_or_send_message(
            message=data.get('message'),
            new_text=progress_text,
            state=state,
            reply_markup=keyboard.as_markup()
        )

        await asyncio.sleep(5)

    if last_exception:
        logger.error(f"Ошибка при запросе всех сервисов: {last_exception}")
        return None, 0, 0

    return available_services, len(services_with_numbers), len(available_services)

async def get_sms_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    user_api_key = get_user_api_key(callback_query.from_user.id)
    user_country_code = get_user_country(callback_query.from_user.id) or "0"
    user_operator = get_user_operator(callback_query.from_user.id) or "any"

    if not user_api_key:
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="⚙️ Настройки", callback_data="settings")
        keyboard.button(text="🔙 Назад", callback_data="back_to_main_menu")
        keyboard.adjust(1)
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Пожалуйста, сначала настройте ваш API ключ в разделе 'Настройки'.",
            state=state,
            reply_markup=keyboard.as_markup()
        )
        return

    logger.info(f"Пользователь {callback_query.from_user.id} начал процесс получения номера.")

    await state.update_data(last_message_id=callback_query.message.message_id, cancel_request=False)
    available_services, total_services_with_numbers, total_services_for_country = await fetch_all_services(user_api_key, user_country_code, state)

    country_name = COUNTRIES.get(user_country_code, 'Неизвестно')
    operator_name = OPERATOR_DISPLAY_NAMES.get(user_operator, 'Любой')

    await state.update_data(total_services_with_numbers=total_services_with_numbers, 
                            total_services_for_country=total_services_for_country,
                            country_name=country_name, 
                            operator_name=operator_name)

    if available_services is None:
        await send_main_menu(callback_query.message, state)
        return

    smshub_api = SmsHubAPI(user_api_key)
    numbers_status = await smshub_api.get_numbers_status(country=user_country_code, operator=user_operator)
    services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}

    services_with_operator = len(services_with_numbers)  # Количество сервисов с учетом настроек оператора

    keyboard = build_service_keyboard(page_number=0, available_services=available_services, services_with_numbers=services_with_numbers)
    message_text = get_service_message_text(total_services_with_numbers, total_services_for_country, services_with_operator, country_name, operator_name)

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=message_text,
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="Markdown"
    )
    await state.set_state(SmsOrderState.waiting_for_service)
    await state.update_data(available_services=available_services)

async def go_back_to_service_selection(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    logger.info(f"Пользователь {callback_query.from_user.id} отменил операцию.")

    await state.update_data(cancel_request=True)

    data = await state.get_data()
    current_task = data.get('current_task')
    if current_task:
        current_task.cancel()

    # Обновите актуальные данные здесь
    available_services = data.get('available_services', [])
    total_services_with_numbers = data.get('total_services_with_numbers', len(available_services))
    total_services_for_country = data.get('total_services_for_country', len(available_services))
    country_name = data.get('country_name', 'Неизвестно')
    operator_name = data.get('operator_name', 'Любой')

    smshub_api = SmsHubAPI(get_user_api_key(callback_query.from_user.id))
    numbers_status = await smshub_api.get_numbers_status(country=get_user_country(callback_query.from_user.id), operator=get_user_operator(callback_query.from_user.id))
    services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}

    services_with_operator = len(services_with_numbers)  # Количество сервисов с учетом настроек оператора

    keyboard = build_service_keyboard(page_number=0, available_services=available_services, services_with_numbers=services_with_numbers)
    message_text = get_service_message_text(total_services_with_numbers, total_services_for_country, services_with_operator, country_name, operator_name)

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=message_text,
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="Markdown"
    )

    await state.set_state(SmsOrderState.waiting_for_service)

async def back_to_main_menu(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    logger.info(f"Пользователь {callback_query.from_user.id} вернулся в главное меню.")

    await state.set_state(None)
    await send_main_menu(callback_query.message, state)

async def service_page_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    page_number = int(callback_query.data.split(":")[1])
    data = await state.get_data()
    available_services = data.get('available_services', [])

    smshub_api = SmsHubAPI(get_user_api_key(callback_query.from_user.id))
    numbers_status = await smshub_api.get_numbers_status(country=get_user_country(callback_query.from_user.id), operator=get_user_operator(callback_query.from_user.id))
    services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}

    services_with_operator = len(services_with_numbers)  # Количество сервисов с учетом настроек оператора

    total_services_with_numbers = data.get('total_services_with_numbers', len(available_services))
    total_services_for_country = data.get('total_services_for_country', len(available_services))
    country_name = data.get('country_name', 'Неизвестно')
    operator_name = data.get('operator_name', 'Любой')

    keyboard = build_service_keyboard(page_number, available_services, services_with_numbers)
    message_text = get_service_message_text(total_services_with_numbers, total_services_for_country, services_with_operator, country_name, operator_name)

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=message_text,
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="Markdown"
    )

async def service_selected_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    service_code = callback_query.data.split(":")[1]
    update_service_popularity(service_code)

    await state.update_data(selected_service=service_code, cancel_request=False)
    task = asyncio.create_task(service_handler_logic(
        callback_query.message, state, user_id=callback_query.from_user.id, service_code=service_code, is_service_selection=True))
    await state.update_data(current_task=task)

async def service_handler(message: types.Message, state: FSMContext, user_id: Optional[int] = None):
    try:
        await message.delete()
    except Exception as e:
        logger.error(f"Не удалось удалить сообщение пользователя: {e}")

    user_input = message.text.strip().lower()

    if user_id is None:
        user_id = message.from_user.id

    logger.info(f"Пользователь {user_id} ввел сервис: {user_input}")

    data = await state.get_data()
    available_services = data.get('available_services', [])

    smshub_api = SmsHubAPI(get_user_api_key(user_id))
    numbers_status = await smshub_api.get_numbers_status(country=get_user_country(user_id), operator=get_user_operator(user_id))
    services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}

    matched_services = [
        (code, name) for code, name in SERVICE_DISPLAY_NAMES.items()
        if code in available_services and (user_input in name.lower() or user_input == code.lower())
    ]

    if matched_services:
        pages = get_service_pages(matched_services)
        page_number = 0
        keyboard = build_page_keyboard(pages, page_number, services_with_numbers)
        
        await state.update_data(matched_services=matched_services)

        await safe_edit_or_send_message(
            message=message,
            new_text="Пожалуйста, выберите один из представленных сервисов:\n_🔴 - нет номеров_",
            state=state,
            reply_markup=keyboard.as_markup(),
            parse_mode="Markdown"
        )
    else:
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="🔙 Назад к сервисам", callback_data="service_page:0")
        await safe_edit_or_send_message(
            message=message,
            new_text="Сервис не найден. Попробуйте ввести код или полное название сервиса.",
            state=state,
            reply_markup=keyboard.as_markup()
        )

def build_page_keyboard(service_pages, page_number: int, services_with_numbers: set) -> InlineKeyboardBuilder:
    keyboard = InlineKeyboardBuilder()
    if page_number < len(service_pages):
        current_page = service_pages[page_number]

        for code, name in current_page:
            # Append a red circle emoji if the service does not have available numbers
            if code not in services_with_numbers:
                name += " 🔴"
            keyboard.button(text=name, callback_data=f"service_select:{code}")

        keyboard.adjust(3)
        
        if len(service_pages) > 1:  # Only show navigation buttons if more than one page exists
            nav_buttons = []
            if page_number > 0:
                nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"search_page:{page_number - 1}"))
            # Centralize page number information
            nav_buttons.append(types.InlineKeyboardButton(text=f"Страница {page_number + 1}/{len(service_pages)}", callback_data="ignore"))
            if page_number < len(service_pages) - 1:
                nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"search_page:{page_number + 1}"))
            keyboard.row(*nav_buttons)
    
    keyboard.row(types.InlineKeyboardButton(text="🔙 Назад к сервисам", callback_data="service_page:0"))
    return keyboard

async def handle_search_page_navigation(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    page_number = int(callback_query.data.split(":")[1])
    data = await state.get_data()
    matched_services = data.get('matched_services', [])

    smshub_api = SmsHubAPI(get_user_api_key(callback_query.from_user.id))
    numbers_status = await smshub_api.get_numbers_status(country=get_user_country(callback_query.from_user.id), operator=get_user_operator(callback_query.from_user.id))
    services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}

    pages = get_service_pages(matched_services)
    keyboard = build_page_keyboard(pages, page_number, services_with_numbers)

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text="Пожалуйста, выберите один из представленных сервисов:\n_🔴 - нет номеров_",
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="Markdown"
    )

async def service_handler_logic(message: types.Message, state: FSMContext, user_id: int, service_code: str, is_service_selection: bool = False):
    logger.info(f"Пользователь {user_id} выбрал сервис: {service_code}")

    user_api_key = get_user_api_key(user_id)
    user_operator = get_user_operator(user_id) or "any"
    user_country_code = get_user_country(user_id) or "0"
    country_name = COUNTRIES.get(user_country_code, user_country_code)

    if not user_api_key:
        await safe_edit_or_send_message(
            message=message,
            new_text="Пожалуйста, сначала настройте ваш API ключ в разделе 'Настройки'.",
            state=state
        )
        await state.set_state(None)
        await send_main_menu(message, state)
        return

    smshub_api = SmsHubAPI(user_api_key)
    usd_to_rub_rate = await get_usd_to_rub_rate()

    max_attempts = 3
    success = False
    last_exception = None

    try:
        for attempt in range(1, max_attempts + 1):
            data = await state.get_data()
            if data.get("cancel_request"):
                logger.info(f"Запрос для пользователя {user_id} был отменен.")
                return

            try:
                progress_text = f"Идет запрос {attempt}/{max_attempts}..."
                keyboard = InlineKeyboardBuilder()
                keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
                keyboard.adjust(1)

                await safe_edit_or_send_message(
                    message=message,
                    new_text=progress_text,
                    state=state,
                    reply_markup=keyboard.as_markup()
                )

                price_info = await smshub_api.get_price_for_service(service_code, country=user_country_code)
                numbers_status = await smshub_api.get_numbers_status(country=user_country_code, operator=user_operator)

                if data.get("cancel_request"):
                    logger.info(f"Запрос для пользователя {user_id} был отменен после получения данных.")
                    return

                if price_info and numbers_status:
                    service_key = f"{service_code}_0"
                    available_numbers = int(numbers_status.get(service_key, 0) or 0)
                    
                    if available_numbers > 0:
                        prices = [float(price_str) for price_str in price_info.keys() if price_str is not None]
                        if prices:
                            min_price_usd = min(prices)
                            max_price_usd = max(prices)
                            min_price_rub = min_price_usd * usd_to_rub_rate if usd_to_rub_rate else 0
                            max_price_rub = max_price_usd * usd_to_rub_rate if usd_to_rub_rate else 0

                            operator_display = OPERATOR_DISPLAY_NAMES.get(user_operator, user_operator)
                            service_display = SERVICE_DISPLAY_NAMES.get(service_code, service_code)

                            keyboard = InlineKeyboardBuilder()
                            keyboard.button(text=f"⬇️ Мин. цена ({min_price_usd:.4f}$)", callback_data=f"select_price:{min_price_usd}")
                            keyboard.button(text=f"⬆️ Макс. цена ({max_price_usd:.4f}$)", callback_data=f"select_price:{max_price_usd}")
                            keyboard.adjust(2)
                            keyboard.row(types.InlineKeyboardButton(text="❌ Отмена", callback_data="cancel_operation"))

                            message_text = (
                                f"*Страна:* `{country_name}`\n"
                                f"*Доступно номеров:* `{available_numbers}`\n"
                                f"*Оператор:* `{operator_display}`\n"
                                f"*Сервис:* `{service_display}`\n"
                                f"*Цены:* от `{min_price_usd:.4f}` $ (₽{min_price_rub:.2f}) до `{max_price_usd:.4f}` $ (₽{max_price_rub:.2f}).\n\n"
                                f"_Выберите максимальную допустимую стоимость покупки с помощью кнопок ниже или введите сумму вручную (например: 0.5). Все суммы указаны в долларах ($):_"
                            )

                            await safe_edit_or_send_message(
                                message=message,
                                new_text=message_text,
                                state=state,
                                reply_markup=keyboard.as_markup(),
                                parse_mode="Markdown"
                            )

                            await state.update_data(
                                service=service_code,
                                service_display=service_display,
                                country_name=country_name,
                                available_numbers=available_numbers,
                                operator_display=operator_display,
                                min_price=min_price_usd,
                                max_price_usd=max_price_usd,
                                min_price_rub=min_price_rub,
                                max_price_rub=max_price_rub,
                                usd_to_rub_rate=usd_to_rub_rate,
                                user_id=user_id
                            )

                            await state.set_state(SmsOrderState.waiting_for_max_price)
                            success = True
                            break
                        else:
                            logger.info(f"Попытка {attempt}: Цены не найдены.")
                            last_exception = "Цены не найдены"
                    else:
                        logger.info(f"Попытка {attempt}: Нет доступных номеров.")
                        last_exception = "Нет доступных номеров"

            except Exception as e:
                logger.error(f"Ошибка при получении данных для сервиса '{service_code}', попытка {attempt}: {e}")
                last_exception = e

            await asyncio.sleep(5)

    except asyncio.CancelledError:
        logger.info(f"Задача для пользователя {user_id} была отменена.")
        return

    if not success:
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="Назад", callback_data="service_page:0")
        await safe_edit_or_send_message(
            message=message,
            new_text=f"Произошла ошибка при обработке запроса: {last_exception}. Попробуйте снова.",
            state=state,
            reply_markup=keyboard.as_markup()
        )

async def price_selected_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    price = float(callback_query.data.split(":")[1])
    await state.update_data(max_price=price)

    await process_number_purchase(callback_query.message, state)

async def max_price_handler(message: types.Message, state: FSMContext):
    max_price_input = message.text.strip()
    data = await state.get_data()
    user_id = data.get('user_id', message.from_user.id)

    try:
        await message.delete()
    except Exception as e:
        logger.error(f"Не удалось удалить сообщение пользователя: {e}")

    logger.info(f"Пользователь {user_id} указал максимальную стоимость: {max_price_input}")

    try:
        max_price = float(max_price_input)
    except ValueError:
        user_data = await state.get_data()
        min_price = user_data.get('min_price', 0)
        max_price_usd = user_data.get('max_price_usd', 0)
        min_price_rub = user_data.get('min_price_rub', 0)
        max_price_rub = user_data.get('max_price_rub', 0)

        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
        keyboard.adjust(1)
        await safe_edit_or_send_message(
            message=message,
            new_text=(
                f"Пожалуйста, введите корректное число для максимальной стоимости. "
                f"От `{min_price:.4f}` $ (₽{min_price_rub:.2f}) до `{max_price_usd:.4f}` $ (₽{max_price_rub:.2f})."
            ),
            state=state,
            reply_markup=keyboard.as_markup(),
            parse_mode="Markdown"
        )
        return

    if max_price < data.get('min_price', 0):
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
        keyboard.adjust(1)
        await safe_edit_or_send_message(
            message=message,
            new_text=f"Максимальная стоимость должна быть не менее `{data.get('min_price', 0):.4f}` $.",
            state=state,
            reply_markup=keyboard.as_markup(),
            parse_mode="Markdown"
        )
        return

    await state.update_data(max_price=max_price)

    await process_number_purchase(message, state)

async def process_number_purchase(message: types.Message, state: FSMContext):
    user_data = await state.get_data()
    user_id = user_data.get('user_id', message.from_user.id)
    service = user_data['service']
    service_display = user_data['service_display']
    country_name = user_data['country_name']
    operator_display = user_data['operator_display']
    max_price = user_data['max_price']
    user_api_key = get_user_api_key(user_id)
    smshub_api = SmsHubAPI(user_api_key)
    user_country_code = get_user_country(user_id) or "0"

    max_attempts = 3
    last_exception = None

    try:
        for attempt in range(1, max_attempts + 1):
            data = await state.get_data()

            if data.get("cancel_request"):
                logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен.")
                return
            
            progress_text = f"Идет запрос {attempt}/{max_attempts} на получение номера..."
            keyboard = InlineKeyboardBuilder()
            keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
            keyboard.adjust(1)

            await safe_edit_or_send_message(
                message=message,
                new_text=progress_text,
                state=state,
                reply_markup=keyboard.as_markup()
            )

            user_operator = get_user_operator(user_id) or "any"

            if data.get("cancel_request"):
                logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен перед выполнением.")
                return

            result = await smshub_api.get_number(service, country=user_country_code, max_price=max_price, operator=user_operator)

            if data.get("cancel_request"):
                logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен.")
                return

            if result and result.startswith("ACCESS_NUMBER"):
                _, activation_id, number = result.split(":")
                logger.info(f"Пользователь {user_id} получил номер: {number}, активация ID: {activation_id}")

                if user_id not in user_activations:
                    user_activations[user_id] = {}
                user_activations[user_id][activation_id] = {
                    'number': number,
                    'status': 'Ожидание SMS',
                    'service': service,
                    'service_display': service_display,
                    'country_name': country_name,
                    'last_update': time.time(),
                    'task': None
                }

                keyboard = InlineKeyboardBuilder()
                keyboard.button(text="📂 Текущие активации", callback_data="current_activations")
                keyboard.button(text="❌ Отменить активацию", callback_data=f"cancel_activation:{activation_id}")
                keyboard.button(text="🔙 Главное меню", callback_data="back_to_main_menu")
                keyboard.adjust(1)

                message_text = (
                    f"*Получен номер:* `{number}`\n"
                    f"*Страна:* `{country_name}`\n"
                    f"*Оператор:* `{operator_display}`\n"
                    f"*Сервис:* `{service_display}`\n"
                    f"*Максимальная стоимость:* `{max_price:.2f}` $ (₽{max_price * user_data['usd_to_rub_rate']:.2f})\n"
                    f"*Статус:* *Ожидание SMS*\n"
                    f"Вы можете управлять активацией или вернуться в главное меню."
                )

                sent_message = await safe_edit_or_send_message(
                    message=message,
                    new_text=message_text,
                    state=state,
                    reply_markup=keyboard.as_markup(),
                    parse_mode="Markdown"
                )
                user_activations[user_id][activation_id]['message_id'] = sent_message.message_id

                await state.set_state(None)

                task = asyncio.create_task(poll_for_sms(
                    bot=message.bot,
                    user_id=user_id,
                    chat_id=message.chat.id,
                    activation_id=activation_id,
                    smshub_api=smshub_api,
                    state=state,               # Передаем state
                    message=message             # Передаем message
                ))
                user_activations[user_id][activation_id]['task'] = task
                return

            elif result == "NO_NUMBERS":
                logger.info(f"Попытка {attempt} из {max_attempts}: нет доступных номеров.")
                last_exception = result
                if attempt == max_attempts:
                    suggestion = (
                        "Попробуйте выбрать 'Любой оператор' в настройках или увеличить максимальную цену."
                        if user_operator != "any" else
                        "Попробуйте увеличить максимальную цену или повторите попытку позже."
                    )
                    keyboard = InlineKeyboardBuilder()
                    keyboard.button(text="Назад", callback_data="service_page:0")
                    await safe_edit_or_send_message(
                        message=message,
                        new_text=f"Нет доступных номеров для оператора {operator_display} по данной цене.\n{suggestion}",
                        state=state,
                        reply_markup=keyboard.as_markup()
                    )
                    return
            else:
                raise Exception("Неожиданный ответ API")

            await asyncio.sleep(5)

    except asyncio.CancelledError:
        logger.info(f"Задача для пользователя {user_id} была отменена.")
        return

    if last_exception and last_exception != "NO_NUMBERS":
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="Назад", callback_data="service_page:0")
        await safe_edit_or_send_message(
            message=message,
            new_text=f"Произошла ошибка при обработке запроса: {last_exception}. Попробуйте снова.",
            state=state,
            reply_markup=keyboard.as_markup()
        )

# Add a handler for the "ignore" callback to silently ignore it
async def ignore_callback_handler(callback_query: types.CallbackQuery):
    try:
        await callback_query.answer()  # Just answer to confirm the action
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

def register_sms_handlers(dp: Dispatcher):
    dp.callback_query.register(get_sms_handler, F.data == "get_sms")
    dp.callback_query.register(go_back_to_service_selection, F.data == "cancel_operation")
    dp.callback_query.register(back_to_main_menu, F.data == "back_to_main_menu")
    dp.callback_query.register(service_page_handler, F.data.startswith("service_page:"))
    dp.callback_query.register(service_selected_handler, F.data.startswith("service_select:"))
    dp.callback_query.register(handle_search_page_navigation, F.data.startswith("search_page:"))
    dp.callback_query.register(price_selected_handler, F.data.startswith("select_price:"))
    dp.callback_query.register(ignore_callback_handler, F.data == "ignore")
    dp.message.register(service_handler, SmsOrderState.waiting_for_service)
    dp.message.register(max_price_handler, SmsOrderState.waiting_for_max_price)









Nov 08 10:35:12 vps1707806210 python[15326]: 2024-11-08 10:35:12,804 - bot.handlers.sms - INFO - Пользователь 389669884 выбрал сервис: ya
Nov 08 10:35:12 vps1707806210 python[15326]: 2024-11-08 10:35:12,808 - aiogram.event - INFO - Update id=600811184 is not handled. Duration 100 ms by bot id=7633673561
Nov 08 10:35:12 vps1707806210 python[15326]: 2024-11-08 10:35:12,808 - aiogram.event - ERROR - Cause exception while process update id=600811184 by bot id=7633673561
Nov 08 10:35:12 vps1707806210 python[15326]: TypeError: errors_handler() missing 1 required positional argument: 'exception'
Nov 08 10:35:12 vps1707806210 python[15326]: Traceback (most recent call last):
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/middlewares/error.py", line 25, in __call__
Nov 08 10:35:12 vps1707806210 python[15326]:     return await handler(event, data)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/middlewares/user_context.py", line 56, in __call__
Nov 08 10:35:12 vps1707806210 python[15326]:     return await handler(event, data)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/fsm/middleware.py", line 42, in __call__
Nov 08 10:35:12 vps1707806210 python[15326]:     return await handler(event, data)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/telegram.py", line 121, in trigger
Nov 08 10:35:12 vps1707806210 python[15326]:     return await wrapped_inner(event, kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/handler.py", line 43, in call
Nov 08 10:35:12 vps1707806210 python[15326]:     return await wrapped()
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.py", line 276, in _listen_update
Nov 08 10:35:12 vps1707806210 python[15326]:     return await self.propagate_event(update_type=update_type, event=event, **kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 146, in propagate_event
Nov 08 10:35:12 vps1707806210 python[15326]:     return await observer.wrap_outer_middleware(_wrapped, event=event, data=kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 141, in _wrapped
Nov 08 10:35:12 vps1707806210 python[15326]:     return await self._propagate_event(
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 166, in _propagate_event
Nov 08 10:35:12 vps1707806210 python[15326]:     response = await observer.trigger(event, **kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/telegram.py", line 121, in trigger
Nov 08 10:35:12 vps1707806210 python[15326]:     return await wrapped_inner(event, kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/handler.py", line 43, in call
Nov 08 10:35:12 vps1707806210 python[15326]:     return await wrapped()
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/bot/handlers/sms.py", line 305, in service_selected_handler
Nov 08 10:35:12 vps1707806210 python[15326]:     await state.update_data(current_task=task)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/fsm/context.py", line 37, in update_data
Nov 08 10:35:12 vps1707806210 python[15326]:     return await self.storage.update_data(key=self.key, data=kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/fsm/storage/base.py", line 186, in update_data
Nov 08 10:35:12 vps1707806210 python[15326]:     await self.set_data(key=key, data=current_data)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/fsm/storage/redis.py", line 114, in set_data
Nov 08 10:35:12 vps1707806210 python[15326]:     self.json_dumps(data),
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/usr/lib/python3.10/json/__init__.py", line 231, in dumps
Nov 08 10:35:12 vps1707806210 python[15326]:     return _default_encoder.encode(obj)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/usr/lib/python3.10/json/encoder.py", line 199, in encode
Nov 08 10:35:12 vps1707806210 python[15326]:     chunks = self.iterencode(o, _one_shot=True)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/usr/lib/python3.10/json/encoder.py", line 257, in iterencode
Nov 08 10:35:12 vps1707806210 python[15326]:     return _iterencode(o, 0)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/usr/lib/python3.10/json/encoder.py", line 179, in default
Nov 08 10:35:12 vps1707806210 python[15326]:     raise TypeError(f'Object of type {o.__class__.__name__} '
Nov 08 10:35:12 vps1707806210 python[15326]: TypeError: Object of type Task is not JSON serializable
Nov 08 10:35:12 vps1707806210 python[15326]: During handling of the above exception, another exception occurred:
Nov 08 10:35:12 vps1707806210 python[15326]: Traceback (most recent call last):
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.py", line 309, in _process_update
Nov 08 10:35:12 vps1707806210 python[15326]:     response = await self.feed_update(bot, update, **kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.py", line 158, in feed_update
Nov 08 10:35:12 vps1707806210 python[15326]:     response = await self.update.wrap_outer_middleware(
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/middlewares/error.py", line 29, in __call__
Nov 08 10:35:12 vps1707806210 python[15326]:     response = await self.router.propagate_event(
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 146, in propagate_event
Nov 08 10:35:12 vps1707806210 python[15326]:     return await observer.wrap_outer_middleware(_wrapped, event=event, data=kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 141, in _wrapped
Nov 08 10:35:12 vps1707806210 python[15326]:     return await self._propagate_event(
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 166, in _propagate_event
Nov 08 10:35:12 vps1707806210 python[15326]:     response = await observer.trigger(event, **kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/telegram.py", line 121, in trigger
Nov 08 10:35:12 vps1707806210 python[15326]:     return await wrapped_inner(event, kwargs)
Nov 08 10:35:12 vps1707806210 python[15326]:   File "/root/smstest/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/handler.py", line 43, in call
Nov 08 10:35:12 vps1707806210 python[15326]:     return await wrapped()
Nov 08 10:35:12 vps1707806210 python[15326]: TypeError: errors_handler() missing 1 required positional argument: 'exception'
Nov 08 10:35:12 vps1707806210 python[15326]: 2024-11-08 10:35:12,919 - bot.api - INFO - Запрос цен для сервиса: ya, страна: 0, валюта: 643
Nov 08 10:35:13 vps1707806210 python[15326]: 2024-11-08 10:35:13,116 - bot.api - INFO - Цены для сервиса ya: {'0': {'ya': {'0.0206': 81, '0.0371': 81, '0.0375': 394, '0.0387': 1, '0.0391': 4, '0.0403': 4, '0.0407': 15, '0.0415': 53, '0.0416': 1117, '0.0475': 39, '0.0515': 15, '0.0520': 93, '0.0528': 371, '0.0529': 97, '0.0531': 1, '0.0532': 3954, '0.0555': 978, '0.0607': 60, '0.0611': 1097}}}
Nov 08 10:35:13 vps1707806210 python[15326]: 2024-11-08 10:35:13,116 - bot.api - INFO - Запрос статуса номеров для страны: 0, оператор: any
Nov 08 10:35:13 vps1707806210 python[15326]: 2024-11-08 10:35:13,242 - bot.api - INFO - Статус номеров: {'baa_0': '36976', 'bax_0': '36017', 'baw_0': '36103', 'aa_0': '25805', 'ac_0': '25811', 'ad_0': '37128', 'ae_0': '34596', 'ah_0': '23748', 'ai_0': '23732', 'ak_0': '37157', 'am_0': '32891', 'an_0': '35347', 'bbl_0': '36966', 'ao_0': '22913', 'bbo_0': '36320', 'bbs_0': '36026', 'at_0': '23705', 'av_0': '5178', 'bbt_0': '36084', 'aw_0': '34760', 'bbv_0': '36094', 'ba_0': '23337', 'bd_0': '31471', 'bcf_0': '36136', 'bh_0': '23664', 'bcg_0': '36023', 'bi_0': '23240', 'bl_0': '35146', 'bm_0': '23757', 'bo_0': '34757', 'bco_0': '36127', 'br_0': '22575', 'bv_0': '35504', 'aat_0': '23113', 'bw_0': '23744', 'bz_0': '34294', 'cb_0': '26028', 'bdb_0': '36098', 'abd_0': '21956', 'bde_0': '36086', 'ce_0': '25618', 'bdi_0': '35461', 'abl_0': '23315', 'bdm_0': '35455', 'cm_0': '37097', 'abk_0': '23259', 'cn_0': '35191', 'abn_0': '23693', 'co_0': '37153', 'abm_0': '23712', 'cr_0': '22931', 'ct_0': '23763', 'cu_0': '23463', 'cy_0': '33530', 'abw_0': '23553', 'abz_0': '23881', 'aby_0': '24056', 'da_0': '19068', 'aca_0': '23701', 'dd_0': '22961', 'de_0': '34794', 'df_0': '34844', 'acd_0': '23657', 'acg_0': '23624', 'dh_0': '35104', 'dj_0': '23729', 'ach_0': '23600', 'do_0': '25793', 'bep_0': '35432', 'dp_0': '34885', 'beq_0': '35675', 'ds_0': '30601', 'dt_0': '20711', 'bes_0': '35458', 'acw_0': '22809', 'bez_0': '35456', 'dz_0': '35236', 'ee_0': '34839', 'en_0': '35107', 'adr_0': '23208', 'es_0': '34273', 'et_0': '34861', 'bfu_0': '35461', 'bft_0': '35430', 'adv_0': '22970', 'ew_0': '34885', 'adw_0': '23289', 'adz_0': '23672', 'ady_0': '23697', 'fb_0': '34169', 'bga_0': '35462', 'fd_0': '31533', 'aee_0': '23711', 'ff_0': '35049', 'aeg_0': '23650', 'bgj_0': '35432', 'aeh_0': '23690', 'aek_0': '23708', 'aej_0': '23029', 'ael_0': '23492', 'bgp_0': '35456', 'fs_0': '35126', 'aes_0': '23710', 'ft_0': '20083', 'fu_0': '34269', 'aeu_0': '23712', 'fx_0': '35355', 'bgw_0': '35460', 'fy_0': '34776', 'fz_0': '34518', 'gb_0': '34770', 'afa_0': '23919', 'gk_0': '23408', 'afl_0': '23712', 'gm_0': '34780', 'bhl_0': '35978', 'bho_0': '35980', 'go_0': '23401', 'bhn_0': '35980', 'gp_0': '33806', 'afp_0': '23654', 'afo_0': '23569', 'gr_0': '17258', 'gs_0': '23551', 'bhw_0': '25535', 'gw_0': '34350', 'afu_0': '23706', 'gx_0': '35161', 'bhx_0': '25221', 'gz_0': '34618', 'hb_0': '34856', 'hc_0': '37442', 'agd_0': '37187', 'hg_0': '34773', 'bii_0': '24763', 'bin_0': '24807', 'bim_0': '24807', 'ho_0': '23763', 'bip_0': '24806', 'agn_0': '23607', 'hu_0': '37042', 'agu_0': '23735', 'agt_0': '23581', 'hw_0': '33892', 'hx_0': '35051', 'hz_0': '34487', 'ahb_0': '23623', 'ahc_0': '23657', 'ig_0': '31885', 'ahe_0': '23684', 'ij_0': '34914', 'il_0': '33808', 'ahl_0': '23667', 'im_0': '37395', 'ahk_0': '23749', 'ahn_0': '23630', 'io_0': '34961', 'ip_0': '35076', 'iq_0': '34430', 'iw_0': '23753', 'ahx_0': '23756', 'ahz_0': '23655', 'ja_0': '23415', 'jc_0': '35529', 'aie_0': '23753', 'jf_0': '34767', 'aif_0': '23761', 'aim_0': '23715', 'ail_0': '23751', 'jo_0': '23192', 'jp_0': '23763', 'ain_0': '23763', 'jr_0': '34348', 'js_0': '23763', 'jv_0': '23747', 'jy_0': '23461', 'aiy_0': '23763', 'aiz_0': '23763', 'ajb_0': '23752', 'kd_0': '23564', 'ajd_0': '23672', 'ke_0': '34564', 'ajc_0': '23695', 'kf_0': '34816', 'kh_0': '23712', 'ajg_0': '23115', 'kj_0': '23706', 'kk_0': '23725', 'aji_0': '23041', 'ajl_0': '23732', 'kt_0': '35390', 'ajt_0': '23686', 'kz_0': '34986', 'akb_0': '23786', 'ake_0': '23750', 'lf_0': '34962', 'akf_0': '23686', 'li_0': '35053', 'lm_0': '23332', 'ls_0': '35074', 'lt_0': '34807', 'lv_0': '34735', 'lx_0': '34620', 'lz_0': '23505', 'ma_0': '6415', 'mb_0': '34442', 'md_0': '15112', 'me_0': '35150', 'mg_0': '24999', 'mi_0': '23566', 'mj_0': '34590', 'mm_0': '33790', 'mo_0': '22230', 'mt_0': '33117', 'mv_0': '23177', 'mw_0': '23591', 'my_0': '34947', 'mz_0': '23367', 'nc_0': '23488', 'nf_0': '35241', 'ng_0': '23189', 'ami_0': '23483', 'nj_0': '23684', 'amk_0': '23714', 'nl_0': '25898', 'amn_0': '23766', 'nq_0': '34528', 'ns_0': '23174', 'nt_0': '22187', 'nv_0': '34923', 'nw_0': '23202', 'amy_0': '23479', 'amx_0': '23731', 'of_0': '24808', 'og_0': '35081', 'oi_0': '29786', 'oj_0': '23356', 'ok_0': '29134', 'ol_0': '35029', 'oo_0': '23246', 'anp_0': '23122', 'ot_0': '27207', 'ov_0': '23347', 'ow_0': '23328', 'aoi_0': '22425', 'pj_0': '23418', 'aoh_0': '21945', 'aok_0': '22628', 'aoj_0': '22597', 'pm_0': '34656', 'aom_0': '22597', 'pn_0': '23425', 'aol_0': '22628', 'po_0': '31412', 'aoo_0': '22628', 'pp_0': '34086', 'aon_0': '22537', 'ps_0': '23368', 'aos_0': '22404', 'aor_0': '22623', 'aou_0': '22628', 'pv_0': '23270', 'aot_0': '22619', 'pw_0': '23499', 'aov_0': '22035', 'qf_0': '34021', 'qh_0': '34951', 'qj_0': '34789', 'apj_0': '21786', 'qp_0': '23462', 'qq_0': '34859', 'qr_0': '31086', 'qs_0': '23233', 'apq_0': '34211', 'qv_0': '23357', 'qw_0': '10482', 'qx_0': '23492', 'apw_0': '22258', 'qz_0': '35088', 'apy_0': '22589', 'aqa_0': '22628', 'rc_0': '22805', 'rd_0': '34554', 're_0': '35161', 'aqd_0': '22800', 'rj_0': '34871', 'rl_0': '34028', 'rm_0': '35045', 'rn_0': '23315', 'ro_0': '23243', 'rq_0': '23453', 'aqq_0': '22499', 'aqr_0': '22577', 'aqt_0': '22628', 'sb_0': '34867', 'sd_0': '35098', 'sg_0': '8899', 'sh_0': '34973', 'sn_0': '34155', 'arr_0': '22563', 'st_0': '35081', 'sv_0': '34151', 'arv_0': '22628', 'sz_0': '23670', 'ta_0': '25277', 'tc_0': '29898', 'asb_0': '37040', 'tg_0': '3721', 'th_0': '35009', 'ti_0': '34985', 'asi_0': '22628', 'tk_0': '34323', 'ask_0': '22628', 'tl_0': '34559', 'tn_0': '34648', 'tp_0': '37142', 'ts_0': '34168', 'tv_0': '23213', 'tw_0': '34840', 'tx_0': '34168', 'ty_0': '23623', 'tz_0': '23294', 'ua_0': '21797', 'ub_0': '21892', 'ue_0': '37112', 'ate_0': '22628', 'ui_0': '34309', 'uk_0': '34791', 'um_0': '23625', 'uq_0': '23143', 'ato_0': '22628', 'us_0': '25848', 'atq_0': '22624', 'ut_0': '23143', 'uu_0': '13452', 'atu_0': '15557', 'ux_0': '23054', 'atx_0': '22628', 'vb_0': '23202', 'vd_0': '35135', 've_0': '34957', 'aug_0': '21509', 'vh_0': '23553', 'auf_0': '22553', 'vi_0': '14972', 'vj_0': '23253', 'vk_0': '4535', 'vl_0': '23253', 'vm_0': '34736', 'vp_0': '34763', 'vq_0': '23543', 'aup_0': '36253', 'auu_0': '22613', 'aut_0': '22410', 'auv_0': '22651', 'vz_0': '23774', 'wa_0': '11193', 'wb_0': '28709', 'wc_0': '34649', 'wd_0': '33583', 'we_0': '36942', 'wp_0': '34120', 'avr_0': '22574', 'wt_0': '35104', 'wu_0': '22640', 'wx_0': '35175', 'wy_0': '23553', 'wz_0': '23253', 'xa_0': '23552', 'xc_0': '23072', 'awc_0': '22574', 'awb_0': '36001', 'xe_0': '34212', 'awe_0': '22558', 'awd_0': '22560', 'awf_0': '22575', 'xk_0': '34807', 'awk_0': '22483', 'xm_0': '23921', 'xn_0': '23736', 'xo_0': '23154', 'xp_0': '22870', 'xr_0': '34289', 'xt_0': '25911', 'aww_0': '22499', 'xx_0': '23205', 'awy_0': '22492', 'awx_0': '22499', 'ya_0': '8453', 'yd_0': '22133', 'ye_0': '22810', 'yf_0': '34121', 'yh_0': '23130', 'axg_0': '34035', 'yk_0': '34442', 'yl_0': '32873', 'ym_0': '25963', 'yo_0': '34644', 'yq_0': '23029', 'yu_0': '34961', 'yw_0': '34136', 'axu_0': '34048', 'yz_0': '34493', 'axy_0': '34125', 'za_0': '34246', 'ayg_0': '34330', 'zh_0': '34909', 'ayk_0': '34168', 'zl_0': '37264', 'zn_0': '37190', 'zo_0': '34879', 'zp_0': '23744', 'ayq_0': '34302', 'zr_0': '37104', 'zs_0': '35057', 'zx_0': '23565', 'azd_0': '34305', 'azs_0': '35951'}