import asyncio
import websockets
import json
import os
from pyrogram import Client,types
import sqlite3

api_id = 20092044
api_hash = "8570570a50fe2f8d51ab511a8df3fb3e"


DB_PATH = "data.db"
chus = "GemPremila"
connection = sqlite3.connect(DB_PATH, check_same_thread=False)

app = Client("bot", api_id=api_id, api_hash=api_hash)

def save_object_content(data, filename="gifts.json"):
    try:
        with open(filename, "w", encoding="utf-8") as json_file:
            json.dump(data, json_file, ensure_ascii=False, indent=4)
        print(f"✅ Data successfully saved to {filename}.")
    except Exception as e:
        print(f"❌ Error saving file: {e}")

def thumb_to_dict(thumb):
    if not thumb:
        return None
    return {
        "file_id": thumb.file_id,
        "file_unique_id": thumb.file_unique_id,
        "width": thumb.width,
        "height": thumb.height,
        "file_size": thumb.file_size
    }

def sticker_to_dict(sticker):
    if not sticker:
        return None
    
    thumbs = []
    if hasattr(sticker, 'thumbs') and sticker.thumbs:
        thumbs = [thumb_to_dict(thumb) for thumb in sticker.thumbs]

    return {
        "file_id": sticker.file_id,
        "file_unique_id": sticker.file_unique_id,
        "file_name": getattr(sticker, 'file_name', None),
        "mime_type": getattr(sticker, 'mime_type', None),
        "file_size": sticker.file_size,
        "date": sticker.date.isoformat() if sticker.date else None,
        "width": sticker.width,
        "height": sticker.height,
        "is_animated": sticker.is_animated,
        "is_video": sticker.is_video,
        "is_premium": getattr(sticker, 'is_premium', None),
        "emoji": sticker.emoji,
        "set_name": sticker.set_name,
        "thumbs": thumbs
    }

def star_gift_to_dict(star_gift):
    return {
        "id": str(star_gift.id),
        "price": star_gift.price,
        "convert_price": getattr(star_gift, 'convert_price', None),
        "available_amount": getattr(star_gift, 'available_amount', None),
        "upgrade_price": getattr(star_gift, 'upgrade_price', None),
        "can_upgrade": getattr(star_gift, 'can_upgrade', None),
        "upgrade_message_id": getattr(star_gift, 'upgrade_message_id', None),
        "total_amount": getattr(star_gift, 'total_amount', None),
        "is_limited": getattr(star_gift, 'is_limited', None),
        "is_sold_out": getattr(star_gift, 'is_sold_out', None),
        "first_sale_date": star_gift.first_sale_date.isoformat() if getattr(star_gift, 'first_sale_date', None) else None,
        "last_sale_date": star_gift.last_sale_date.isoformat() if getattr(star_gift, 'last_sale_date', None) else None,
        "sticker": sticker_to_dict(star_gift.sticker)
    }
    
    
def save_temp(value, filename="temp.txt"):
    with open(filename, "w", encoding="utf-8") as f:
        f.write(str(value))
        
        
def load_temp(filename="temp.txt"):
    if not os.path.exists(filename):
        return None
    with open(filename, "r", encoding="utf-8") as f:
        return f.read()


async def update_gifts_periodically():
    while True:
        try:
            print("⏳ Updating gift list...")
            available_gifts = await app.get_available_gifts()
            gift_list_json = [
                star_gift_to_dict(gift) for gift in available_gifts if (not getattr(gift, 'is_sold_out', True))
            ]
            save_object_content(gift_list_json)
                            
            upList = ""
            changeList = ""
            ok = False
            
            for res in available_gifts:  
                cursor = connection.cursor()

                query = f"SELECT id,msg_id,stats,emoji,nft FROM data2 WHERE id = {res.id}"  # کوئری خود را جایگزین کنید
                cursor.execute(query)
                quesry_res = cursor.fetchone()

                
                
                if not res.is_sold_out:
                    file_id = res.sticker.file_id
                    file_path = os.path.join("sticker", f"{res.id}.tgs")
                    
                    if not os.path.exists(file_path):
                        try:
                            print(f"  -> Downloading sticker for gift {res.id}...")
                            await app.download_media(file_id, file_name=file_path)
                        except Exception as e:
                            print(f"  -> ❌ Error downloading sticker for gift {res.id}: {e}")
            
                    try:
                        if res.is_sold_out:
                            continue
                        cursor = connection.cursor()
                        cursor.execute("SELECT id FROM data WHERE id = ?", (res.id,))
                        if cursor.fetchone() is None:
                            # sticker = await app.send_sticker(chus, f"sticker/{res.id}.tgs")
                            ok = True
                            cursor.execute("INSERT INTO data (id, nft) VALUES (?, ?)", (res.id, "text"))
                            connection.commit()
                    except Exception as e:
                        print(f"⚠️ Failed to buy gift {res.id}: {e}")
            
                if(quesry_res):
                    if(quesry_res[4] == 0 and res.upgrade_price):
                        upList = upList + f"<emoji id={quesry_res[3]}>🎁</emoji> can now be upgraded to NFT with <code>{res.upgrade_price:,}</code> <emoji id=5954135079662916434>⭐️</emoji>\n\n"
                        update_query2 = "UPDATE data2 SET nft = ? WHERE id = ?"
                        values2 = (res.upgrade_price,res.id)  # مقادیر جدید و شرط
                        try:
                            cursor.execute(update_query2, values2)
                            connection.commit()
                            print(f"{cursor.rowcount} رکورد به‌روز شد.")
                        except Exception as e:
                            print(f"❌ Error: {e}")
                            
                    else:
                        if(quesry_res[4] != res.upgrade_price and res.upgrade_price):
                            changeList = changeList + f"<emoji id={quesry_res[3]}>🎁</emoji> upgrade <s>{quesry_res[4]:,}</s> → <code>{res.upgrade_price:,}</code> <emoji id=5954135079662916434>⭐️</emoji>\n\n"
                            update_query2 = "UPDATE data2 SET nft = ? WHERE id = ?"
                            values2 = (res.upgrade_price,res.id)  # مقادیر جدید و شرط
                            try:
                                cursor.execute(update_query2, values2)
                                connection.commit()
                                print(f"{cursor.rowcount} رکورد به‌روز شد.")
                            except Exception as e:
                                print(f"❌ Error: {e}")
                                
            
            if(upList != ''):
                x = await app.send_message(chus, f'''<b>NFT upgrade is avalible!</b> <emoji id=6296367896398399651>✅</emoji>\n\n{upList}<emoji id=5963312935148195483>💎</emoji><a href="https://t.me/GemPremilaRobot">Buy Stars</a> |<emoji id=5470170700096495711>🖼</emoji> <a href="https://t.me/portals/market?startapp=478lfj">Buy-Sell gifts</a>\n<emoji id=5258332798409783582>🚀</emoji>  @GemPremila |<emoji id=6032937473162614352>🎁</emoji><a href="tg://premium_multigift?ref=">Send a Gift</a>''',link_preview_options=types.LinkPreviewOptions(is_disabled=True))  
                save_temp(x.id)
            if(changeList != ''):
                del_msg = load_temp()
                await app.delete_messages(chus,int(del_msg))
                    
                await app.send_message(chus, f'''<b>NFT upgrade price change!</b>\n\n{changeList}<emoji id=5963312935148195483>💎</emoji><a href="https://t.me/GemPremilaRobot">Buy Stars</a> |<emoji id=5470170700096495711>🖼</emoji> <a href="https://t.me/portals/market?startapp=478lfj">Buy-Sell gifts</a>\n<emoji id=5258332798409783582>🚀</emoji>  @GemPremila |<emoji id=6032937473162614352>🎁</emoji><a href="tg://premium_multigift?ref=">Send a Gift</a>''',link_preview_options=types.LinkPreviewOptions(is_disabled=True))  

                        
            if ok:
                await app.send_message(chus, '''<emoji id="6032937473162614352">🎁</emoji> گیفت‌های محدود در دسترس قرار گرفتند!

برای خرید، از ربات سفارش بدین،
روی لینک زیر کلیک کنید <emoji id="5231102735817918643">👇</emoji> 

https://t.me/GemPremilaRobot?start=gift

<emoji id="6032937473162614352">🎁</emoji> @GemPremila <emoji id="5956148757899776734">⭐</emoji>️''',link_preview_options=types.LinkPreviewOptions(is_disabled=True))
                ok = False
            
            
            
        except Exception as e:
            print(f"❌ Error in periodic gift list update: {e}")
        
        await asyncio.sleep(60)

async def handler(websocket):
    async for message in websocket:
        try:
            data = json.loads(message)
            if data["action"] == "send_gift":
                chat_id = data["chat_id"]
                gift_id = int(data["gift_id"])
                count = int(data.get("count", 1))
                success = 0
                for i in range(count):
                    try:
                        await app.send_gift(chat_id=chat_id, gift_id=gift_id)
                        success += 1
                    except Exception as e:
                        await websocket.send(json.dumps({
                            "status": "error",
                            "message": f"❌ Failed on iteration {i+1}: {str(e)}"
                        }))
                        break
                await websocket.send(json.dumps({"status": "ok"}))
            else:
                await websocket.send(json.dumps({"status": "unknown_action"}))
        except Exception as e:
            await websocket.send(json.dumps({"status": "error", "message": str(e)}))

async def websocket_server():
    async with websockets.serve(handler, "localhost", 8765):
        print("✅ WebSocket server is ready: ws://localhost:8765")
        await asyncio.Future()

async def main():
    await app.start()
    print("✅ Pyrogram client connected successfully.")
    
    server_task = asyncio.create_task(websocket_server())
    update_task = asyncio.create_task(update_gifts_periodically())
    
    await asyncio.gather(server_task, update_task)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    except (KeyboardInterrupt, SystemExit):
        print("\nExiting application...")
