import asyncio
from telethon import TelegramClient
from telethon.errors import FloodWaitError

CHANNEL = "doostanone"
API_ID = 12228029
API_HASH = "9bf063457a4fa9e962a8bf5e45dbc487"
PHONE = "+989156247445"

TG_PASSWORD = "Hi110100159&"

client = TelegramClient("ktbm_session", API_ID, API_HASH)

async def sync_chunk(entity, min_id):
    return await client.get_messages(
        entity,
        limit=100,
        min_id=min_id,
        reverse=True
    )

async def safe_sync():
    entity = await client.get_entity(CHANNEL)

    last_id = 0

    while True:
        try:
            msgs = await sync_chunk(entity, last_id)

            if not msgs:
                print("✅ DONE")
                break

            for msg in msgs:

                # ذخیره در DB
                print("SYNC:", msg.id)

                last_id = msg.id

            await asyncio.sleep(1)

        except FloodWaitError as e:
            print("⏳ FLOOD:", e.seconds)
            await asyncio.sleep(e.seconds)

        except Exception as e:
            print("❌ CONNECTION LOST:", e)

            # 🔥 مهم: reconnect واقعی
            try:
                await client.disconnect()
                await asyncio.sleep(3)
                await client.connect()
            except:
                pass

            await asyncio.sleep(5)

async def main():
    await client.start()
    print("🚀 START")

    await safe_sync()

    await client.run_until_disconnected()

asyncio.run(main())