import uuid
from datetime import datetime, timezone
from typing import Any, Optional
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from modules.bots.models import BotUser
from modules.broadcasts.models import BroadcastCampaign, BroadcastRecipient


class BroadcastRepository:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def create_campaign(
        self,
        tenant_id: uuid.UUID,
        bot_id: uuid.UUID,
        title: str,
        message_text: str,
        target_filter: dict[str, Any],
        inline_keyboard: Optional[list[list[dict[str, Any]]]] = None,
        media_type: str = "none",
        media_url: Optional[str] = None,
        scheduled_at: Optional[datetime] = None,
        rate_limit_per_second: int = 25,
    ) -> BroadcastCampaign:
        campaign = BroadcastCampaign(
            id=uuid.uuid4(),
            tenant_id=tenant_id,
            bot_id=bot_id,
            title=title,
            status="draft",
            target_filter=target_filter,
            message_text=message_text,
            inline_keyboard=inline_keyboard,
            media_type=media_type,
            media_url=media_url,
            scheduled_at=scheduled_at,
            rate_limit_per_second=rate_limit_per_second,
            total_recipients=0,
            sent_count=0,
            delivered_count=0,
            failed_count=0,
        )
        self.db.add(campaign)
        await self.db.commit()
        await self.db.refresh(campaign)
        return campaign

    async def get_campaign_by_id(
        self,
        campaign_id: uuid.UUID,
        tenant_id: Optional[uuid.UUID] = None,
    ) -> Optional[BroadcastCampaign]:
        stmt = select(BroadcastCampaign).where(BroadcastCampaign.id == campaign_id)
        if tenant_id:
            stmt = stmt.where(BroadcastCampaign.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        return res.scalar_one_or_none()

    async def list_campaigns(self, tenant_id: uuid.UUID) -> list[BroadcastCampaign]:
        res = await self.db.execute(
            select(BroadcastCampaign)
            .where(BroadcastCampaign.tenant_id == tenant_id)
            .order_by(BroadcastCampaign.created_at.desc())
        )
        return list(res.scalars().all())

    async def update_campaign(self, campaign: BroadcastCampaign, **updates: Any) -> BroadcastCampaign:
        for k, v in updates.items():
            if v is not None:
                setattr(campaign, k, v)
        await self.db.commit()
        await self.db.refresh(campaign)
        return campaign

    # --- Audience Selection & Opt-Out Enforcement ---
    async def get_eligible_audience(
        self,
        bot_id: uuid.UUID,
        target_filter: dict[str, Any],
    ) -> list[BotUser]:
        """
        Retrieves eligible recipient bot users, strictly enforcing opt-out and blocked flags.
        """
        stmt = select(BotUser).where(
            BotUser.bot_id == bot_id,
            BotUser.is_blocked.is_(False),
            BotUser.is_opted_out.is_(False),
        )

        # Filter by language if specified
        target_locale = target_filter.get("locale")
        if target_locale:
            stmt = stmt.where(BotUser.preferred_locale == target_locale)

        res = await self.db.execute(stmt)
        return list(res.scalars().all())

    async def create_recipients(
        self,
        campaign_id: uuid.UUID,
        users: list[BotUser],
    ) -> list[BroadcastRecipient]:
        recipients = [
            BroadcastRecipient(
                id=uuid.uuid4(),
                campaign_id=campaign_id,
                bot_user_id=u.id,
                telegram_chat_id=u.telegram_user_id,
                status="pending",
                attempts=0,
            )
            for u in users
        ]
        self.db.add_all(recipients)
        await self.db.commit()
        return recipients

    async def get_pending_recipients(
        self,
        campaign_id: uuid.UUID,
        limit: int = 100,
    ) -> list[BroadcastRecipient]:
        res = await self.db.execute(
            select(BroadcastRecipient)
            .where(
                BroadcastRecipient.campaign_id == campaign_id,
                BroadcastRecipient.status == "pending",
            )
            .limit(limit)
        )
        return list(res.scalars().all())

    async def update_recipient(
        self,
        recipient: BroadcastRecipient,
        status: str,
        error_message: Optional[str] = None,
        delivered_at: Optional[datetime] = None,
    ) -> BroadcastRecipient:
        recipient.status = status
        recipient.attempts += 1
        recipient.error_message = error_message
        if delivered_at:
            recipient.delivered_at = delivered_at
        await self.db.commit()
        return recipient

    async def get_recipient_stats(self, campaign_id: uuid.UUID) -> dict[str, Any]:
        res = await self.db.execute(
            select(BroadcastRecipient.status, func.count(BroadcastRecipient.id))
            .where(BroadcastRecipient.campaign_id == campaign_id)
            .group_by(BroadcastRecipient.status)
        )
        counts = {row[0]: row[1] for row in res.fetchall()}

        errors_res = await self.db.execute(
            select(BroadcastRecipient.error_message, func.count(BroadcastRecipient.id))
            .where(
                BroadcastRecipient.campaign_id == campaign_id,
                BroadcastRecipient.status.in_(["failed", "blocked"]),
            )
            .group_by(BroadcastRecipient.error_message)
        )
        errors = {row[0] or "Unknown Error": row[1] for row in errors_res.fetchall()}

        return {
            "counts": counts,
            "errors": errors,
        }

    async def set_user_opt_out(
        self,
        bot_id: uuid.UUID,
        telegram_user_id: int,
        opt_out: bool = True,
    ) -> bool:
        res = await self.db.execute(
            select(BotUser).where(
                BotUser.bot_id == bot_id,
                BotUser.telegram_user_id == telegram_user_id,
            )
        )
        user = res.scalar_one_or_none()
        if user:
            user.is_opted_out = opt_out
            await self.db.commit()
            return True
        return False
