# aiogram
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.enums import ParseMode
from aiogram.fsm.storage.redis import RedisStorage, DefaultKeyBuilder, StorageKey
from aiogram.types import BotCommand

# cfg
from decouple import config

# db
from shared import ORM

# another
import logging, pytz
from urllib.parse import quote


logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
TELEGRAM_API_TIMEOUT = 120.0


def build_telegram_proxy_url(proxy_value: str | None) -> str | None:
    if proxy_value is None:
        return None

    proxy_value = proxy_value.strip()
    if not proxy_value:
        return None

    parts = proxy_value.split(":")
    if len(parts) < 3:
        raise ValueError(
            "TELEGRAM_BOT_PROXY must be in format protocol(http/socks5):ip:port:user:pass"
        )

    protocol, host, port, *auth_parts = parts
    if not protocol or not host or not port:
        raise ValueError(
            "TELEGRAM_BOT_PROXY must be in format protocol(http/socks5):ip:port:user:pass"
        )

    username = auth_parts[0] if len(auth_parts) > 0 else ""
    password = ":".join(auth_parts[1:]) if len(auth_parts) > 1 else ""

    if username or password:
        auth = f"{quote(username, safe='')}:{quote(password, safe='')}@"
    else:
        auth = ""

    return f"{protocol}://{auth}{host}:{port}"


telegram_proxy_url = build_telegram_proxy_url(
    config("TELEGRAM_BOT_PROXY", default="")
)
bot_session = (
    AiohttpSession(proxy=telegram_proxy_url, timeout=TELEGRAM_API_TIMEOUT)
    if telegram_proxy_url
    else AiohttpSession(timeout=TELEGRAM_API_TIMEOUT)
)

if telegram_proxy_url:
    logger.info(
        "Telegram Bot API proxy enabled for host %s",
        telegram_proxy_url.rsplit("@", 1)[-1],
    )

redis_url = config("REDIS_URL")
bot = Bot(
    token=config("TOKEN"),
    default=DefaultBotProperties(parse_mode=ParseMode.HTML),
    session=bot_session,
)
storage = RedisStorage.from_url(redis_url)
storage.key_builder = DefaultKeyBuilder(with_bot_id=True)
dp = Dispatcher(storage=storage)

start_command = [BotCommand(command="/start", description="🔄 Перезапустить бота")]
tz = pytz.timezone(config("TIMEZONE"))
orm = ORM()
