import logging
import re
from telegram import Bot, Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

TOKEN = "8723794166:AAFfpSWjUJ44Bi_CvTpagf8ZOwp-bW515vs"

logging.basicConfig(level=logging.INFO)
user_data = {}

SKIP_TAGS = ["زیرنویس_چسبیده", "زیرنویس_چسبیده_فارسی", "بدون_سانسور", "پیشنهادی", "دوبله_فارسی"]


def start(bot, update):
    uid = update.message.from_user.id
    user_data[uid] = {}
    update.message.reply_text("Hi \n\nبرای فیلم: /f بزن\nبرای سریال: /s بزن")


def film_mode(bot, update):
    uid = update.message.from_user.id
    user_data[uid] = {"mode": "film", "videos": [], "trailer": None}
    update.message.reply_text("حالت فیلم\n\nپوستر آماده رو فوروارد کن، بعد تیزر و ویدیوها رو بفرست، آخرش /d بزن")


def serial_mode(bot, update):
    uid = update.message.from_user.id
    user_data[uid] = {"mode": "serial", "videos": [], "trailer": None}
    update.message.reply_text("حالت سریال\n\nپوستر آماده رو فوروارد کن، بعد /d بزن")


def extract_info(caption):
    info = {
        "name_fa": "", "name_en": "", "year": "",
        "imdb": "", "genres": [], "country": "",
        "summary": "", "seasons": "", "episodes": ""
    }
    if not caption:
        return info

    # نام فارسی
    fa = re.search(r'«([^«»\n]+)»', caption)
    if fa:
        info["name_fa"] = fa.group(1).strip()

    if not info["name_fa"]:
        fa2 = re.findall(r'#([\u0600-\u06FF_]+)', caption)
        fa2 = [f for f in fa2 if f not in SKIP_TAGS]
        if fa2:
            info["name_fa"] = fa2[0].replace('_', ' ')

    # نام انگلیسی + سال
    en = re.search(r'([A-Za-z][A-Za-z0-9\s\:\-\,\.\']{3,}?)\s+(20\d{2}|19\d{2})', caption)
    if en:
        info["name_en"] = en.group(0).strip()
        info["year"] = en.group(2)

    if not info["name_en"]:
        en2 = re.search(r'#([A-Za-z][A-Za-z0-9_]+)\s+(20\d{2}|19\d{2})', caption)
        if en2:
            info["name_en"] = en2.group(1).replace('_', ' ') + " " + en2.group(2)
            info["year"] = en2.group(2)

    if not info["year"]:
        yr = re.search(r'\b(20\d{2}|19\d{2})\b', caption)
        if yr:
            info["year"] = yr.group(1)

    # امتیاز IMDB
    imdb = re.search(r'(\d+\.?\d*)\s*/\s*10', caption)
    if imdb:
        info["imdb"] = imdb.group(1)
    else:
        imdb2 = re.search(r'(\d+\.?\d*)\s*از\s*10', caption)
        if imdb2:
            info["imdb"] = imdb2.group(1)
        else:
            imdb3 = re.search(r'(?:IMDB|IMDb|امتیاز)[^\d]*(\d+\.?\d*)', caption)
            if imdb3:
                info["imdb"] = imdb3.group(1)

    # ژانر — اول از خط صریح "ژانر :" می‌خونیم، چون مطمئن‌تره
    genres = []
    genre_line = re.search(r'ژانر[^\n:]*:\s*([^\n]+)', caption)
    if genre_line:
        raw = genre_line.group(1)
        parts = re.split(r'[|,،]', raw)
        genres = [p.strip().lstrip('#').strip() for p in parts if p.strip()]
        # حذف چیزهایی که با /حرف فارسی ندارن یا تو لیست skip هستن
        genres = [g for g in genres if g and g not in SKIP_TAGS]

    if not genres:
        all_tags = re.findall(r'#([\u0600-\u06FF_]+)', caption)
        genres = [g for g in all_tags if g not in SKIP_TAGS]

    info["genres"] = genres

    # کشور
    country_match = re.search(r'(?:محصول کشور|کشور سازنده|محصول)[^\n:]*:?\s*#?([^\n]+)', caption)
    if country_match:
        c = country_match.group(1).strip()
        c = re.sub(r'[#@]', '', c)
        c = c.split('|')[0].split(',')[0].strip()
        info["country"] = c

    # خلاصه داستان
    summary_match = re.search(
        r'(?:خلاصه داستان|خلاصه)[^\n]*:?\s*\n+([\s\S]+?)(?:\n\s*\n|\n\s*[-_]{3,}|\n\s*[@]|\Z)',
        caption
    )
    if summary_match:
        info["summary"] = summary_match.group(1).strip()

    if not info["summary"]:
        summary_inline = re.search(
            r'(?:خلاصه داستان|خلاصه)[^\n]*?:\s*(.+?)(?:\n\s*[@]|\Z)',
            caption, re.DOTALL
        )
        if summary_inline:
            info["summary"] = summary_inline.group(1).strip()

    # فصل و قسمت
    seasons = re.search(r'(\d+)\s*فصل', caption)
    episodes = re.search(r'(\d+)\s*قسمت', caption)
    if seasons:
        info["seasons"] = seasons.group(1)
    if episodes:
        info["episodes"] = episodes.group(1)

    return info


def make_film_caption(info):
    genres_str = " | ".join(["#" + g for g in info["genres"]]) if info["genres"] else ""
    country_str = "#" + info["country"] if info["country"] else ""
    return (
        "⚡️ فیلم : « " + info["name_fa"] + " »\n"
        "🎬 " + info["name_en"] + "\n"
        "#" + info["name_fa"].replace(" ", "_") + "\n"
        "📤کیفیت : 1080p | 720p | 480p \n"
        "🎭 ژانر : " + genres_str + "\n"
        "📜#زیرنویس_چسبیده \n"
        "🏅امتیاز : " + info["imdb"] + " از 10\n"
        "🌎محصول کشور: " + country_str + "\n\n"
        "🗯 خلاصه داستان :\n" + info["summary"] + "\n\n\n"
        "⚠️ بزنید رو دانلود فیلم و وقتی وارد ربات شدید رو استارت بزنید تا فایل رو بهتون بده👇\n\n\n"
        "💎 برای دانلود فیلم کلیک کنید\n\n\n"
        "✅ @RoyayeFilm"
    )


def make_serial_caption(info):
    genres_str = " | ".join(["#" + g for g in info["genres"]]) if info["genres"] else ""
    country_str = "#" + info["country"] if info["country"] else ""
    seasons = info["seasons"] if info["seasons"] else "0"
    episodes = info["episodes"] if info["episodes"] else "0"
    return (
        "⚡️ سریال : « " + info["name_fa"] + " »\n"
        "🎬 " + info["name_en"] + "\n"
        "#" + info["name_fa"].replace(" ", "_") + "\n"
        "📤کیفیت : 480p | 720p\n"
        "🎭 ژانر : " + genres_str + "\n"
        "📜#زیرنویس_چسبیده \n"
        "🏅امتیاز : " + info["imdb"] + " از 10\n"
        "🌎محصول کشور: " + country_str + "\n"
        "📺تعداد فصل : " + seasons + " فصل | " + episodes + " قسمت \n\n"
        "🗯 خلاصه داستان :\n" + info["summary"] + "\n\n\n"
        "⚠️ بزنید رو دانلود فیلم و وقتی وارد ربات شدید رو استارت بزنید تا فایل رو بهتون بده👇\n\n"
        "💎فصل اول ( 480 ) _  ( 720 )\n\n"
        "💎فصل دوم ( 480 ) _  ( 720 )\n\n"
        "💎فصل سوم ( 480 ) _  ( 720 )\n\n"
        "💎فصل چهارم ( 480 ) _  ( 720 )\n\n\n"
        "✅@RoyayeFilm"
    )


def make_video_caption(name_fa, quality):
    return (
        "🎬 نام فیلم \" " + name_fa + " \"\n"
        "📑 #زیر_نویس_چسبیده \n"
        "‼️ بدون سانسور و حذفیات 💥\n"
        "♻️ کیفیت : " + quality + "\n"
        "🆔 @RoyayeFilm"
    )


def make_trailer_caption(name_fa):
    return "🟣 #تیزر_فیلم \" " + name_fa + " \"\n\n@RoyayeFilm"


def get_quality(caption):
    if not caption:
        return ""
    if "1080" in caption:
        return "1080p"
    elif "720" in caption:
        return "720p"
    elif "480" in caption:
        return "480p"
    return ""


def receive_message(bot, update):
    uid = update.message.from_user.id
    if uid not in user_data or "mode" not in user_data[uid]:
        update.message.reply_text("اول /f یا /s بزن")
        return

    msg = update.message

    if msg.photo:
        caption = msg.caption or ""
        user_data[uid]["poster"] = msg.photo[-1].file_id
        user_data[uid]["poster_caption"] = caption
        update.message.reply_text("پوستر دریافت شد!")

    elif msg.video:
        caption = msg.caption or ""
        quality = get_quality(caption)
        if any(x in caption for x in ["تیزر", "تریلر", "teaser", "trailer", "Trailer", "Teaser"]):
            user_data[uid]["trailer"] = msg.video.file_id
            update.message.reply_text("تیزر دریافت شد!")
        else:
            user_data[uid]["videos"].append({"file_id": msg.video.file_id, "quality": quality, "is_video": True})
            update.message.reply_text("ویدیو " + quality + " دریافت شد!")

    elif msg.document:
        caption = msg.caption or ""
        quality = get_quality(caption)
        user_data[uid]["videos"].append({"file_id": msg.document.file_id, "quality": quality, "is_video": False})
        update.message.reply_text("فایل " + quality + " دریافت شد!")


def done(bot, update):
    uid = update.message.from_user.id
    if uid not in user_data or "mode" not in user_data[uid]:
        update.message.reply_text("اول /f یا /s بزن")
        return

    data = user_data[uid]
    mode = data.get("mode")
    poster_caption = data.get("poster_caption", "")
    poster_file_id = data.get("poster")

    if not poster_file_id:
        update.message.reply_text("پوستر نفرستادی!")
        return

    info = extract_info(poster_caption)

    if mode == "film":
        caption = make_film_caption(info)
    else:
        caption = make_serial_caption(info)

    bot.send_photo(chat_id=update.message.chat_id, photo=poster_file_id, caption=caption)

    # این بخش دیگه برای هر دو حالت (فیلم و سریال) اجرا می‌شه
    if data.get("trailer"):
        bot.send_video(
            chat_id=update.message.chat_id,
            video=data["trailer"],
            caption=make_trailer_caption(info["name_fa"])
        )
    for v in data.get("videos", []):
        video_cap = make_video_caption(info["name_fa"], v["quality"])
        if v["is_video"]:
            bot.send_video(chat_id=update.message.chat_id, video=v["file_id"], caption=video_cap)
        else:
            bot.send_document(chat_id=update.message.chat_id, document=v["file_id"], caption=video_cap)

    user_data[uid] = {}
    update.message.reply_text("done")


def main():
    updater = Updater(TOKEN)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("f", film_mode))
    dp.add_handler(CommandHandler("s", serial_mode))
    dp.add_handler(CommandHandler("d", done))
    dp.add_handler(MessageHandler(Filters.all, receive_message))
    print("ربات شروع به کار کرد!")
    updater.start_polling()
    updater.idle()


if __name__ == "__main__":
    main()
