"""Instagram downloader — posts, reels, stories via yt-dlp.
v3.0: enabled with quality selection, metadata extraction."""
from __future__ import annotations

import logging
import re
import time

from telegram import InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto, Update
from telegram.constants import ParseMode
from telegram.ext import CallbackQueryHandler, ContextTypes, MessageHandler, filters

from bot.handlers.dl_utils import (
    TEMP_DIR,
    cache_get,
    cache_set,
    dl_via_ytdlp,
    download_file,
    escape_md,
    extract_info_ytdlp,
    format_size,
    get_http_client,
)

logger = logging.getLogger(__name__)

INSTAGRAM_RE = re.compile(
    r"(?:https?://)?(?:www\.)?instagram\.com/(?:p|reel|tv|stories)/([a-zA-Z0-9_\-]+)",
    re.IGNORECASE,
)

_pending: dict[tuple[int, int], dict] = {}
PENDING_TTL = 300


async def instagram_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    message = update.message
    if not message or not message.text:
        return

    urls = INSTAGRAM_RE.findall(message.text)
    if not urls:
        return

    status = await message.reply_text("🔍 دریافت اطلاعات پست...")

    for shortcode in urls:
        url = f"https://instagram.com/p/{shortcode}"
        try:
            info = await extract_info_ytdlp(url)
        except Exception:
            await status.edit_text(f"❌ پست دریافت نشد. شاید خصوصی یا حذف شده.")
            continue

        if not info:
            await status.edit_text(f"❌ پست دریافت نشد.")
            continue

        thumb = info.get("thumbnail", "")
        caption_text = info.get("description", info.get("title", ""))[:300]
        author = info.get("uploader", info.get("channel_id", "unknown"))

        caption = f"📸 **اینستاگرام**\n👤 {author}"
        if caption_text:
            caption += f"\n\n{caption_text}"
        caption = caption[:1024]

        # Find media
        entries = info.get("entries", [])
        media_urls = []
        if entries:
            for entry in entries:
                if entry.get("url"):
                    media_urls.append(entry["url"])
        # Single video/reel
        if info.get("url") and not media_urls:
            media_urls = [info["url"]]

        if not media_urls and thumb:
            # Image only
            path = await download_file(thumb, f"ig_{shortcode}.jpg")
            if path:
                try:
                    with open(path, "rb") as f:
                        await message.reply_photo(f, caption=caption)
                finally:
                    path.unlink(missing_ok=True)
            else:
                await message.reply_text(caption)
            continue

        # Download media
        for i, url in enumerate(media_urls[:5]):
            ext = "mp4" if ".mp4" in url or "video" in url else "jpg"
            path = await download_file(url, f"ig_{shortcode}_{i}.{ext}")
            if path:
                try:
                    with open(path, "rb") as f:
                        if ext == "mp4":
                            kb = InlineKeyboardMarkup([
                                [InlineKeyboardButton("🔗 مشاهده", url=f"https://instagram.com/p/{shortcode}")],
                            ])
                            await message.reply_video(f, caption=caption, reply_markup=kb)
                        else:
                            await message.reply_photo(f, caption=caption)
                finally:
                    path.unlink(missing_ok=True)

    try:
        await status.delete()
    except Exception:
        pass


def register(app) -> None:
    app.add_handler(
        MessageHandler(filters.TEXT & ~filters.COMMAND, instagram_handler),
        group=-2,
    )
    logger.info("Instagram downloader registered (v3.0)")
