"""
Обработчик callback-кнопок и шаринга контактов.

Маршрутизирует callback-и по типу (consent_* и др.).
"""
import datetime
import logging
from sqlalchemy import select
from app.database import async_session
from app.models import BotConversation, BotMessage
from app.max_api import max_api
from app.keyboards import consent_keyboard

logger = logging.getLogger(__name__)


async def handle_callback(user_id: int, callback_id: str, callback_data: dict) -> None:
    """Маршрутизация callback-кнопок (consent_* → consent handler)."""
    async with async_session() as db:
        result = await db.execute(
            select(BotConversation)
            .where(BotConversation.user_id == user_id)
            .order_by(BotConversation.id.desc())
            .limit(1)
        )
        conv = result.scalar_one_or_none()

    conv_id = conv.id if conv else 0

    if callback_id.startswith("consent_"):
        from app.handlers.consent import handle_consent_callback
        await handle_consent_callback(user_id, conv_id, callback_id)
    else:
        await max_api.send_message(
            user_id,
            "Извините, я не распознала действие. Пожалуйста, воспользуйтесь кнопками.",
            conversation_id=conv_id,
        )


async def handle_contact_share(
    user_id: int,
    conv_id: int,
    phone: str,
    vcf_info: str = "",
    vcf_data: dict = None,
    contact_hash: str = "",
) -> None:
    """Обработка шаринга контакта из мессенджера: парсинг VCF, сохранение в BotUser."""
    if vcf_data is None:
        vcf_data = {}
    async with async_session() as db:
        from app.models import BotUser
        user_result = await db.execute(select(BotUser).where(BotUser.id == user_id))
        user = user_result.scalar_one_or_none()
        if user:
            user.phone = phone or user.phone
            if vcf_data.get("first_name"):
                user.first_name = vcf_data["first_name"]
            if vcf_data.get("last_name"):
                user.last_name = vcf_data["last_name"]
            if vcf_data.get("patronymic"):
                user.patronymic = vcf_data["patronymic"]
            if vcf_data.get("email"):
                user.email = vcf_data["email"]
            if vcf_data.get("organization"):
                user.organization = vcf_data["organization"]
            if vcf_data.get("address"):
                user.address = vcf_data["address"]
            if vcf_info:
                user.vcf_raw = vcf_info
            if contact_hash:
                user.contact_hash = contact_hash
                user.phone_verified = True
            if phone:
                user.phone_verified = True

        msg = BotMessage(
            conversation_id=conv_id,
            direction="incoming",
            text=f"[Контакт поделен] {phone or vcf_data.get('phone', '')}",
            created_at=datetime.datetime.utcnow(),
        )
        db.add(msg)

        conv_result = await db.execute(
            select(BotConversation).where(BotConversation.id == conv_id)
        )
        conv = conv_result.scalar_one_or_none()
        if conv:
            conv.state = "awaiting_inquiry"

        await db.commit()

    await max_api.send_message(
        user_id,
        "Спасибо! Ваш контакт получен.\n\n"
        "Опишите, пожалуйста, суть вашего обращения — "
        "расскажите подробнее, чем мы можем вам помочь.",
        conversation_id=conv_id,
    )
