import asyncio
import io
import os
import urllib.parse
import google.generativeai as genai
import requests
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from dotenv import load_dotenv
from telegram import Bot

load_dotenv()

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHANNEL_ID = os.getenv("CHANNEL_ID")

genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel("gemini-1.5-flash-latest")


async def generate_lexitales_content():
    """تولید داستان کوتاه دو زبانه، نکات آموزشی و پرامپت تصویر"""
    prompt = """
    تو یک نویسنده خلاق و استاد آموزش زبان هستی.
    یک داستان بسیار کوتاه، طنز و بامزه (حداکثر ۷۰ کلمه) بنویس.
    
    خروجی باید دقیقاً طبق فرمت زیر باشد:

    🇮🇷 **ترجمه:**
    <ترجمه روان فارسی>

    
    📖 **English:**
    <متن انگلیسی داستان>


    💡 **LexiNotes:**
    • Word/Idiom 1: معنی و کاربرد کوتاه
    • Word/Idiom 2: معنی و کاربرد کوتاه
    • Word/Idiom 3: معنی و کاربرد کوتاه

    [PROMPT] <یک پرامپت دقیق انگلیسی برای ساخت عکس کارتونی و مرتبط>
    """

    response = model.generate_content(prompt)
    full_text = response.text.strip()

    if "[PROMPT]" in full_text:
        content, img_prompt = full_text.split("[PROMPT]")
        return content.strip(), img_prompt.strip()
    else:
        return full_text, "A colorful humorous digital illustration for a story"


def generate_image_bytes(image_prompt: str):
    """تولید تصویر با کیفیت بالا از Pollinations.ai"""
    encoded_prompt = urllib.parse.quote(image_prompt)
    url = f"https://pollinations.ai/p/{encoded_prompt}?width=1024&height=1024&seed=42&model=flux"

    try:
        response = requests.get(url, timeout=30)
        if response.status_code == 200:
            return io.BytesIO(response.content)
    except Exception as e:
        print(f"Error fetching image: {e}")
    return None


async def post_to_channel():
    """ارسال پست خودکار به کانال تلگرام"""
    print("در حال تولید داستان جدید LexiTales...")
    bot = Bot(token=TELEGRAM_BOT_TOKEN)

    try:
        content, img_prompt = await generate_lexitales_content()
        image_bytes = generate_image_bytes(img_prompt)

        caption_text = f"{content}\n\n📚 Join @LexiTales"

        if image_bytes:
            await bot.send_photo(
                chat_id=CHANNEL_ID,
                photo=image_bytes,
                caption=caption_text,
                parse_mode="Markdown",
            )
            print("پست تصویری با موفقیت منتشر شد!")
        else:
            await bot.send_message(
                chat_id=CHANNEL_ID, text=caption_text, parse_mode="Markdown"
            )
            print("پست متنی منتشر شد.")

    except Exception as e:
        print(f"خطا در ارسال پست: {e}")


async def main():
    scheduler = AsyncIOScheduler()

    # ارسال پست در ۳ زمان اصلی: ۱۰:۰۰، ۱۶:۰۰ و ۲۱:۰۰
    scheduler.add_job(post_to_channel, "cron", hour=10, minute=0)
    scheduler.add_job(post_to_channel, "cron", hour=16, minute=0)
    scheduler.add_job(post_to_channel, "cron", hour=21, minute=0)

    scheduler.start()
    print("LexiTales Bot active and scheduled...")

    # برای تست بلافاصله پس از اجرا، خط زیر را آن‌کامنت کنید:
    await post_to_channel()

    while True:
        await asyncio.sleep(3600)


if __name__ == "__main__":
    asyncio.run(main())