#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
سكربت تنظيف مصنع KODO
يحذف جميع بيانات التجربة:
  - Webhooks لجميع البوتات المصنوعة
  - جداول PostgreSQL
  - ملفات SQLite للكوبوتات
"""

import asyncio
import aiohttp
import psycopg2
import glob
import os
import sys

# ─── إعدادات الاتصال (من config.py) ───────────────────────
DB_USER  = "kodo"
DB_PASS  = "MahdeFab1YssR"
DB_HOST  = "localhost"
DB_PORT  = "5432"
DB_NAME  = "kodo_factory"

FACTORY_DIR = os.path.dirname(os.path.abspath(__file__))

# ─── جداول PostgreSQL بالترتيب الصحيح (الأبناء أولاً) ──────
TABLES_TO_TRUNCATE = [
    "cobot_funded_subscriptions",
    "cobot_funded_channels",
    "cobot_mandatory_channels",
    "cobot_users",
    "funded_subscriptions",
    "funded_channels",
    "mandatory_channels",
    "button_settings",
    "broadcast_settings",
    "bot_groups",
    "bot_transfers",
    "bots",
    "factory_settings",
    "users",
]


# ════════════════════════════════════════════════════════════
#              1. حذف Webhooks للبوتات المصنوعة
# ════════════════════════════════════════════════════════════

async def delete_webhooks(tokens: list[str]) -> tuple[int, int]:
    ok = failed = 0
    async with aiohttp.ClientSession() as session:
        for token in tokens:
            try:
                url = f"https://api.telegram.org/bot{token}/deleteWebhook"
                async with session.post(url, timeout=aiohttp.ClientTimeout(total=10)) as r:
                    data = await r.json()
                    if data.get("ok"):
                        ok += 1
                    else:
                        failed += 1
            except Exception:
                failed += 1
    return ok, failed


def get_all_bot_tokens() -> list[str]:
    try:
        conn = psycopg2.connect(
            dbname=DB_NAME, user=DB_USER,
            password=DB_PASS, host=DB_HOST, port=DB_PORT
        )
        cur  = conn.cursor()
        cur.execute("SELECT token FROM bots")
        tokens = [row[0] for row in cur.fetchall()]
        cur.close()
        conn.close()
        return tokens
    except Exception as e:
        print(f"  ⚠️  تعذّر قراءة الـ tokens: {e}")
        return []


# ════════════════════════════════════════════════════════════
#              2. تنظيف جداول PostgreSQL
# ════════════════════════════════════════════════════════════

def truncate_postgres() -> int:
    try:
        conn = psycopg2.connect(
            dbname=DB_NAME, user=DB_USER,
            password=DB_PASS, host=DB_HOST, port=DB_PORT
        )
        conn.autocommit = False
        cur = conn.cursor()
        for table in TABLES_TO_TRUNCATE:
            try:
                cur.execute(f"TRUNCATE TABLE {table} RESTART IDENTITY CASCADE")
            except Exception as e:
                print(f"  ⚠️  {table}: {e}")
                conn.rollback()
        conn.commit()
        cur.close()
        conn.close()
        return len(TABLES_TO_TRUNCATE)
    except Exception as e:
        print(f"  ❌ فشل تنظيف PostgreSQL: {e}")
        return 0


# ════════════════════════════════════════════════════════════
#              3. حذف ملفات SQLite
# ════════════════════════════════════════════════════════════

def delete_sqlite_files() -> int:
    pattern = os.path.join(FACTORY_DIR, "cobots", "*", "database", "*.db")
    files   = glob.glob(pattern)
    deleted = 0
    for f in files:
        try:
            os.remove(f)
            print(f"  🗑  {os.path.relpath(f, FACTORY_DIR)}")
            deleted += 1
        except Exception as e:
            print(f"  ⚠️  {f}: {e}")
    return deleted


# ════════════════════════════════════════════════════════════
#                        Main
# ════════════════════════════════════════════════════════════

async def main():
    print("=" * 55)
    print("  🧹  سكربت تنظيف مصنع KODO")
    print("=" * 55)
    print()
    print("⚠️  سيتم حذف جميع البيانات بشكل نهائي!")
    print()

    confirm = input("اكتب  YES  للمتابعة: ").strip()
    if confirm != "YES":
        print("❌ تم الإلغاء.")
        sys.exit(0)

    print()

    # ── خطوة 1: Webhooks ──────────────────────────────────
    print("🔌 جاري قراءة tokens البوتات المصنوعة...")
    tokens = get_all_bot_tokens()
    print(f"   عدد البوتات: {len(tokens)}")

    if tokens:
        print("🌐 جاري حذف الـ Webhooks...")
        ok, failed = await delete_webhooks(tokens)
        print(f"   ✅ تم: {ok}  |  ❌ فشل: {failed}")
    else:
        print("   لا توجد بوتات مسجّلة.")

    print()

    # ── خطوة 2: PostgreSQL ────────────────────────────────
    print("🗄️  جاري تنظيف جداول PostgreSQL...")
    count = truncate_postgres()
    print(f"   ✅ تم تنظيف {count} جدول.")

    print()

    # ── خطوة 3: SQLite ────────────────────────────────────
    print("📁 جاري حذف ملفات SQLite...")
    deleted = delete_sqlite_files()
    if deleted == 0:
        print("   لا توجد ملفات.")
    else:
        print(f"   ✅ تم حذف {deleted} ملف.")

    print()
    print("=" * 55)
    print("  ✅  اكتمل التنظيف. المصنع جاهز للإطلاق!")
    print("=" * 55)
    print()
    print("▶️  لتشغيل المصنع:")
    print("   python3 kodo.py")
    print()


if __name__ == "__main__":
    asyncio.run(main())
