# !/usr/bin/env python
from typing import Final, Any

import aiohttp
from bs4 import BeautifulSoup
from random_user_agent.user_agent import UserAgent

class Parser:
    URL: Final[str] = "https://xms.miatel.ru"
    AGENT: Final[str] = UserAgent().get_random_user_agent()

    def __init__(self, user: str, password: str):
        self.user = user
        self.password = password

    async def get_balance(self):
        headers = {
            "User-Agent": self.AGENT,
            "Content-Type": "application/cbor",
            "Origin": "https://xms.miatel.ru",
            "Accept": "application/cbor",
            "Content-Type": "application/cbor",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
        }

        async with aiohttp.ClientSession() as session:
            login_payload = {
                "username": self.user,
                "password": self.password
            }

            async with session.post(f"{self.URL}/oauth/token", headers=headers, data=login_payload) as response:
                if not response.ok:
                    return f"Error: HTTP {response.status}"

            async with session.get(f"{self.URL}/balance") as resp:
                data = await resp.text()
                print(data)
                if "empty" in data:
                    return 0.0
                soup = BeautifulSoup(data,"html.parser")
                print(soup)
                element = soup.find("tbody", class_ ="text-right")
                number = ''.join(el if el.isdigit() else ' ' for el in element.text).split()
                return int(number)  import asyncio
import shelve

from aiogram import Bot, Dispatcher, types
from aiogram.dispatcher import handler

from config import USER, BOT_TOKEN
from parser import Parser

DB = shelve.open("database", writeback=True)

if DB.get("clients") is None:
    DB["clients"] = set()


async def report_loop(bot: Bot) -> None:
    """Запускается каждые 10 минут и проверяет корректна(более 5т.р.) ли сумма денежных средств на счету chesnok """
    while True:
        for login, password in USER.items():
            try:
                value = await Parser(user=login, password=password).get_balance()
                if isinstance(value, str):
                    for client in DB["clients"]:
                        await bot.send_message(client, value, parse_mode=types.ParseMode.MARKDOWN)
                else:
                    if value < 5000:
                        for client in DB["clients"]:
                            await bot.send_message(client, f"Сумма денежных средств на счету chesnok: {value}")
            except Exception as e:
                # обработка ошибок
                pass

        await asyncio.sleep(15)  # ждать 10 минут


async def start_handler(message: types.Message) -> None:
    """Приветствие нового пользователя и добавление его в базу."""
    DB["clients"].add(message.chat.id)
    await message.answer(
        f"Привет, {message.from_user.get_mention(as_html=True)} 👋!",
        parse_mode=types.ParseMode.HTML,
    )


async def exit_handler(message: types.Message) -> None:
    """Удаление пользователя из базы."""
    if message.chat.id in DB["clients"]:
        DB["clients"].remove(message.chat.id)
        await message.answer(
            f"Пользователь, {message.from_user.get_mention(as_html=True)} успешно отписался.",
            parse_mode=types.ParseMode.HTML,
        )
    else:
        await message.answer(
            f"Пользователь, {message.from_user.get_mention(as_html=True)} не был найден.",
            parse_mode=types.ParseMode.HTML,
        )


async def main() -> None:
    bot = Bot(token=BOT_TOKEN)
    try:
        dispatcher = Dispatcher(bot=bot)
        dispatcher.register_message_handler(start_handler, commands={"start", "restart"})
        dispatcher.register_message_handler(exit_handler, commands={"exit"})
        asyncio.create_task(report_loop(bot))
        await dispatcher.start_polling()
    finally:
        DB.close()
        await bot.close()


if __name__ == '__main__':
    asyncio.run(main())