import json
from pathlib import Path
import re
from typing import Optional, Sequence
from uuid import UUID
import httpx
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import NotFoundError, AppException, ValidationError
from core.logging import get_logger
from modules.emojis.models import CustomEmoji, EmojiPack
from modules.emojis.repository import CustomEmojiRepository
from modules.emojis.schemas import (
    BulkEmojiImportRequest,
    BulkEmojiImportResponse,
    CreateEmojiPackRequest,
    EmojiValidationRequest,
    EmojiValidationResponse,
    EmojiPackResponse,
    EmojiPackDetailResponse,
    CustomEmojiResponse,
)

logger = get_logger(__name__)
SEED_DATA_FILE = Path(__file__).resolve().parent / "seed_data" / "curated_emojis.json"


class EmojiService:
    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = CustomEmojiRepository(db)

    async def search(
        self,
        query: Optional[str] = None,
        category: Optional[str] = None,
        limit: int = 50,
        offset: int = 0,
    ) -> Sequence[CustomEmoji]:
        return await self.repo.search(query=query, category=category, limit=limit, offset=offset)

    async def get_categories(self) -> Sequence[str]:
        return await self.repo.get_categories()

    @staticmethod
    def format_html(custom_emoji_id: str, fallback_emoji: str = "✨") -> str:
        """Formats custom emoji for Telegram HTML parse mode."""
        return f'<tg-emoji emoji-id="{custom_emoji_id}">{fallback_emoji}</tg-emoji>'

    @staticmethod
    def format_markdown(custom_emoji_id: str, fallback_emoji: str = "✨") -> str:
        """Formats custom emoji for Telegram MarkdownV2 parse mode."""
        return f"![{fallback_emoji}](tg://emoji?id={custom_emoji_id})"

    @staticmethod
    def validate_emoji(req: EmojiValidationRequest) -> EmojiValidationResponse:
        """
        Validates Telegram custom emoji IDs and tags.
        Custom emoji IDs must be valid numeric strings representing a 64-bit unsigned integer.
        """
        errors = []
        emoji_id = req.custom_emoji_id
        fallback = "✨"

        if req.formatted_tag:
            tag = req.formatted_tag.strip()
            # Try HTML: <tg-emoji emoji-id="12345">✨</tg-emoji>
            html_m = re.search(r'<tg-emoji\s+emoji-id="(\d+)">([^<]*)</tg-emoji>', tag)
            # Try Markdown: ![✨](tg://emoji?id=12345)
            md_m = re.search(r'!\[([^\]]*)\]\(tg:\/\/emoji\?id=(\d+)\)', tag)

            if html_m:
                emoji_id = html_m.group(1)
                fallback = html_m.group(2) or "✨"
            elif md_m:
                fallback = md_m.group(1) or "✨"
                emoji_id = md_m.group(2)
            else:
                errors.append("Invalid Telegram custom emoji tag format")

        if not emoji_id:
            errors.append("Missing custom_emoji_id")
        else:
            if not emoji_id.isdigit():
                errors.append("custom_emoji_id must be a numeric string")
            else:
                val = int(emoji_id)
                if val <= 0 or val >= 2**64:
                    errors.append("custom_emoji_id is out of range for a 64-bit Telegram emoji ID")

        is_valid = len(errors) == 0
        html_tag = f'<tg-emoji emoji-id="{emoji_id}">{fallback}</tg-emoji>' if is_valid else None
        md_tag = f"![{fallback}](tg://emoji?id={emoji_id})" if is_valid else None

        return EmojiValidationResponse(
            is_valid=is_valid,
            custom_emoji_id=emoji_id if is_valid else None,
            fallback_emoji=fallback,
            html_tag=html_tag,
            markdown_tag=md_tag,
            errors=errors,
        )

    async def bulk_import(self, req: BulkEmojiImportRequest) -> BulkEmojiImportResponse:
        imported_count = 0
        updated_count = 0
        errors_count = 0
        details = []

        packs_cache = {}

        for item in req.emojis:
            # 1. Validate ID
            if not item.custom_emoji_id.isdigit():
                errors_count += 1
                details.append(f"Skipped {item.name}: ID '{item.custom_emoji_id}' is not numeric")
                continue

            # 2. Resolve pack
            pack_name = item.pack_name or req.default_pack_name
            pack_id = None
            if pack_name:
                if pack_name not in packs_cache:
                    pack = await self.repo.get_or_create_pack(
                        name=pack_name.lower().replace(" ", "_"),
                        title=pack_name,
                        is_animated=item.is_animated,
                    )
                    packs_cache[pack_name] = pack.id
                pack_id = packs_cache[pack_name]

            # 3. Upsert
            existing = await self.repo.get_by_custom_emoji_id(item.custom_emoji_id)
            if existing:
                await self.repo.upsert_emoji(
                    custom_emoji_id=item.custom_emoji_id,
                    name=item.name,
                    fallback_emoji=item.fallback_emoji,
                    category=item.category,
                    is_animated=item.is_animated,
                    pack_id=pack_id,
                )
                updated_count += 1
            else:
                await self.repo.upsert_emoji(
                    custom_emoji_id=item.custom_emoji_id,
                    name=item.name,
                    fallback_emoji=item.fallback_emoji,
                    category=item.category,
                    is_animated=item.is_animated,
                    pack_id=pack_id,
                )
                imported_count += 1

        await self.db.flush()
        return BulkEmojiImportResponse(
            imported_count=imported_count,
            updated_count=updated_count,
            errors_count=errors_count,
            details=details,
        )

    async def list_packs(self, limit: int = 50, offset: int = 0) -> list[EmojiPackResponse]:
        pack_rows = await self.repo.list_packs(limit=limit, offset=offset)
        return [
            EmojiPackResponse(
                id=pack.id,
                name=pack.name,
                title=pack.title,
                is_animated=pack.is_animated,
                is_video=pack.is_video,
                emojis_count=count,
                created_at=pack.created_at,
            )
            for pack, count in pack_rows
        ]

    async def get_pack_detail(self, pack_id: UUID) -> EmojiPackDetailResponse:
        pack = await self.repo.get_pack_by_id(pack_id)
        if not pack:
            raise NotFoundError("Emoji pack not found")
        emojis = await self.repo.get_pack_emojis(pack_id)
        return EmojiPackDetailResponse(
            id=pack.id,
            name=pack.name,
            title=pack.title,
            is_animated=pack.is_animated,
            is_video=pack.is_video,
            emojis=[CustomEmojiResponse.model_validate(e) for e in emojis],
            created_at=pack.created_at,
        )

    async def create_pack(self, req: CreateEmojiPackRequest) -> EmojiPackResponse:
        pack = await self.repo.create_pack(
            name=req.name.lower().replace(" ", "_"),
            title=req.title,
            is_animated=req.is_animated,
            is_video=req.is_video,
        )
        return EmojiPackResponse(
            id=pack.id,
            name=pack.name,
            title=pack.title,
            is_animated=pack.is_animated,
            is_video=pack.is_video,
            emojis_count=0,
            created_at=pack.created_at,
        )

    async def delete_pack(self, pack_id: UUID) -> None:
        pack = await self.repo.get_pack_by_id(pack_id)
        if not pack:
            raise NotFoundError("Emoji pack not found")
        await self.repo.delete_pack(pack)

    async def seed_default_emojis(self) -> int:
        """Seeds curated emojis from seed_data/curated_emojis.json if database has fewer than 10 emojis."""
        existing = await self.search(limit=10)
        if len(existing) >= 10:
            return len(existing)

        if not SEED_DATA_FILE.exists():
            return 0

        with open(SEED_DATA_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)

        emojis_data = data.get("emojis", [])
        synced = 0
        default_pack = await self.repo.get_or_create_pack(
            name="telegram_curated",
            title="Curated Premium Emojis",
            is_animated=True,
        )

        for e in emojis_data:
            cid = str(e.get("custom_emoji_id"))
            if not cid.isdigit():
                continue
            await self.repo.upsert_emoji(
                custom_emoji_id=cid,
                name=e.get("name", "Custom Emoji"),
                fallback_emoji=e.get("emoji", "✨"),
                category=e.get("category", "general"),
                is_animated=e.get("is_animated", True),
                pack_id=default_pack.id,
            )
            synced += 1

        await self.db.flush()
        return synced


    async def sync_pack_from_telegram(
        self,
        pack_name: str,
        bot_token: str,
        category: str = "general",
    ) -> dict:
        """
        Fetches an emoji pack from Telegram Bot API via getStickerSet
        and syncs all custom_emoji_id values into database.
        """
        url = f"https://api.telegram.org/bot{bot_token}/getStickerSet"
        async with httpx.AsyncClient(timeout=15.0) as client:
            resp = await client.get(url, params={"name": pack_name})
            data = resp.json()

        if not data.get("ok"):
            err_desc = data.get("description", "Failed to retrieve sticker set")
            raise AppException(f"Telegram API Error: {err_desc}", status_code=400)

        result = data.get("result", {})
        pack_title = result.get("title", pack_name)
        is_animated = result.get("is_animated", True)
        is_video = result.get("is_video", False)
        stickers = result.get("stickers", [])

        # Create/Get pack record
        pack = await self.repo.get_or_create_pack(
            name=pack_name,
            title=pack_title,
            is_animated=is_animated,
            is_video=is_video,
        )

        synced_count = 0
        for idx, sticker in enumerate(stickers):
            custom_id = sticker.get("custom_emoji_id")
            if not custom_id:
                continue

            fallback = sticker.get("emoji", "✨")
            name = f"{pack_title} #{idx + 1}"
            await self.repo.upsert_emoji(
                custom_emoji_id=str(custom_id),
                name=name,
                fallback_emoji=fallback,
                category=category,
                is_animated=is_animated,
                pack_id=pack.id,
            )
            synced_count += 1

        await self.db.commit()
        logger.info(
            "custom_emoji_pack_synced",
            pack_name=pack_name,
            synced_count=synced_count,
        )

        return {
            "pack_name": pack_name,
            "title": pack_title,
            "is_animated": is_animated,
            "synced_emojis_count": synced_count,
        }
