import asyncio
import logging
from typing import Any, Dict, List
import httpx
from aiogram import Bot
from aiogram.types import CopyTextButton, InlineKeyboardButton, InlineKeyboardMarkup

from config import config
from database import Database
from utils import (
    build_sms_hash,
    clean_phone_number,
    detect_sms_language,
    extract_otp_code,
    format_group_otp_message,
    mask_phone_middle_3,
)

logger = logging.getLogger(__name__)


def parse_sms_panel_response(
    payload: Any,
    phone_field: str = "number",
    sender_field: str = "sender",
    text_field: str = "message",
    data_key: str = "data",
) -> List[Dict[str, str]]:
    """
    Parse SMS items from any SMS Panel API JSON structure using per-panel field names
    with automatic fallback to common keys.
    """
    if isinstance(payload, list):
        items = payload
    elif isinstance(payload, dict):
        items = (
            payload.get(data_key)
            if data_key and data_key in payload
            else payload.get("data", payload.get("messages", payload.get("aaData", [])))
        )
    else:
        items = []

    parsed = []
    if not isinstance(items, list):
        return parsed

    for item in items:
        if not isinstance(item, dict):
            continue
        raw_phone = str(
            item.get(phone_field)
            or item.get("number")
            or item.get("phone")
            or item.get("to")
            or ""
        )
        sender = str(
            item.get(sender_field)
            or item.get("sender")
            or item.get("service")
            or item.get("from")
            or "SMS"
        )
        text = str(
            item.get(text_field)
            or item.get("message")
            or item.get("text")
            or item.get("sms")
            or ""
        )
        phone = clean_phone_number(raw_phone)
        if phone and text:
            parsed.append({"phone": phone, "sender": sender, "text": text})
    return parsed


async def _poll_single_panel(
    client: httpx.AsyncClient,
    panel: Dict[str, Any],
    bot: Bot,
    db: Database,
    bot_link: str,
) -> None:
    """Poll one SMS panel independently so one slow panel never blocks others."""
    headers = {}
    params = {}
    api_key = panel.get("api_key") or ""
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
        params["api_key"] = api_key

    try:
        resp = await client.get(panel["api_url"], params=params, headers=headers)
        if resp.status_code != 200:
            return
        messages = parse_sms_panel_response(
            resp.json(),
            phone_field=panel.get("phone_field", "number"),
            sender_field=panel.get("sender_field", "sender"),
            text_field=panel.get("text_field", "message"),
            data_key=panel.get("data_key", "data"),
        )
        for msg in messages:
            otp_code = extract_otp_code(msg["text"])
            sms_lang = detect_sms_language(msg["text"])
            sms_hash = build_sms_hash(msg["phone"], msg["sender"], msg["text"])
            result = await db.process_incoming_otp(
                phone_number=msg["phone"],
                service_hint=msg["sender"],
                otp_code=otp_code,
                sms_text=msg["text"],
                sms_language=sms_lang,
                sms_hash=sms_hash,
                panel_name=panel["name"],
            )
            if result:
                await dispatch_otp_notifications(bot, db, result, bot_link)
    except Exception as exc:
        logger.error("SMS panel '%s' polling error: %s", panel.get("name"), exc)


async def sms_poller_loop(bot: Bot, db: Database) -> None:
    """
    Concurrently poll ALL active SMS panels stored in the database and dispatch
    all incoming OTPs into the SAME OTP group and to the matching user in the bot.
    """
    bot_me = await bot.get_me()
    bot_link = f"https://t.me/{bot_me.username}" if bot_me.username else config.otp_group_link

    async with httpx.AsyncClient(timeout=15) as client:
        while True:
            try:
                panels = await db.get_active_sms_panels()
                if panels:
                    tasks = [
                        _poll_single_panel(client, panel, bot, db, bot_link)
                        for panel in panels
                    ]
                    await asyncio.gather(*tasks, return_exceptions=True)
            except Exception as exc:
                logger.error("Multi-panel poller loop error: %s", exc)

            await asyncio.sleep(config.sms_poll_interval)


async def dispatch_otp_notifications(
    bot: Bot, db: Database, ctx: Dict[str, Any], bot_link: str
) -> None:
    """
    1. User Bot DM: Full phone number, full OTP code, detected SMS language, full SMS text,
       and one-tap Copy buttons.
    2. Shared OTP Group: Receives OTPs from ALL active SMS panels cleanly — NO full SMS text;
       only Country ISO + Service Logo/Name + 3-digit masked number (or Admin's custom text),
       with click-to-copy buttons for Number and OTP.
    """
    phone = ctx["phone_number"]
    otp_code = ctx["otp_code"]
    sms_text = ctx["sms_text"]
    sms_language = ctx.get("sms_language", "Unknown")
    service_name = ctx["service_name"]
    service_icon = ctx["service_icon"]
    iso_code = ctx["iso_code"]
    flag = ctx["country_flag"]
    earned = ctx["earned_amount"]
    user_id = ctx["locked_by"]

    # 1. Direct message to User (Full Number + Full OTP + Language + Full SMS)
    if user_id:
        user_kb = InlineKeyboardMarkup(
            inline_keyboard=[
                [
                    InlineKeyboardButton(
                        text=f"📋 Copy OTP ({otp_code})",
                        copy_text=CopyTextButton(text=otp_code),
                    ),
                    InlineKeyboardButton(
                        text="📋 Copy Number",
                        copy_text=CopyTextButton(text=phone),
                    ),
                ]
            ]
        )
        safe_sms = (
            sms_text.replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
        )
        user_msg = (
            f"✅ <b>New OTP Received!</b>\n\n"
            f"{service_icon} <b>Service:</b> {service_name}\n"
            f"{flag} <b>Country:</b> {iso_code}\n"
            f"🌐 <b>Language:</b> {sms_language}\n"
            f"📱 <b>Number:</b> <code>{phone}</code>\n"
            f"🔑 <b>OTP Code:</b> <code>{otp_code}</code>\n"
            f"💰 <b>Earned:</b> +{config.currency_symbol}{earned:.2f}\n\n"
            f"💬 <b>Full SMS:</b>\n<blockquote>{safe_sms}</blockquote>"
        )
        try:
            await bot.send_message(chat_id=user_id, text=user_msg, reply_markup=user_kb, parse_mode="HTML")
        except Exception as exc:
            logger.warning("Could not DM user %s: %s", user_id, exc)

    # 2. Shared OTP Group (Receives from ALL SMS Panels — NO full SMS text; click-to-copy)
    if config.otp_group_id:
        mask_replacement = await db.get_setting("mask_replacement", config.default_mask_text)
        masked_num = mask_phone_middle_3(phone, replacement=mask_replacement)
        group_text = format_group_otp_message(
            service_icon=service_icon,
            service_name=service_name,
            iso_code=iso_code,
            flag=flag,
            phone_number=phone,
            mask_replacement=mask_replacement,
        )
        group_kb = InlineKeyboardMarkup(
            inline_keyboard=[
                [
                    InlineKeyboardButton(
                        text=f"{service_icon} {service_name} ({masked_num})",
                        copy_text=CopyTextButton(text=phone),
                    )
                ],
                [
                    InlineKeyboardButton(
                        text="🔑 Copy OTP",
                        copy_text=CopyTextButton(text=otp_code),
                    ),
                    InlineKeyboardButton(
                        text="🤖 Open Bot",
                        url=bot_link,
                    ),
                ],
            ]
        )
        try:
            await bot.send_message(
                chat_id=config.otp_group_id,
                text=group_text,
                reply_markup=group_kb,
                parse_mode="HTML",
            )
        except Exception as exc:
            logger.warning("Could not post to OTP group %s: %s", config.otp_group_id, exc)
