"""
سكربت تصفير مشروع KODO Factory
يحذف كل بيانات المشروع من PostgreSQL + ملفات SQLite للبوتات المصنوعة.

⚠️ تحذير: هذا الإجراء لا يمكن التراجع عنه!

طريقة التشغيل:
    python3 reset_project.py
"""

import asyncio
import os
import glob
import sys

# ====== إعداد المسارات ======
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)

from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text

try:
    from config import DATABASE_URL
except Exception as e:
    print(f"❌ تعذر قراءة DATABASE_URL من config.py: {e}")
    sys.exit(1)

# ====== جداول المشروع في PostgreSQL ======
# الترتيب مهم: نحذف الجداول التابعة أولاً (بسبب المفاتيح الأجنبية)
TABLES = [
    "bot_subscriptions",
    "payment_transactions",
    "user_balances",
    "payment_packages",
    "payment_settings",
    "cobot_funded_subscriptions",
    "cobot_funded_channels",
    "cobot_mandatory_channels",
    "funded_subscriptions",
    "funded_channels",
    "mandatory_channels",
    "broadcast_settings",
    "bot_groups",
    "button_settings",
    "factory_settings",
    "bot_transfers",
    "cobot_users",
    "bots",
    "users",
]

# ====== مجلدات SQLite للبوتات المصنوعة ======
COBOT_DB_DIRS = [
    os.path.join(BASE_DIR, "cobots", "communication", "database"),
    os.path.join(BASE_DIR, "cobots", "download",      "database"),
    os.path.join(BASE_DIR, "cobots", "decor",         "database"),
    os.path.join(BASE_DIR, "cobots", "buttons",       "database"),
    os.path.join(BASE_DIR, "cobots", "transcoding",   "database"),
    os.path.join(BASE_DIR, "cobots", "translation",   "database"),
    os.path.join(BASE_DIR, "cobots", "ai",            "database"),
    os.path.join(BASE_DIR, "cobots", "factory",       "database"),
]


async def reset_postgres():
    """تصفير جداول PostgreSQL مع الحفاظ على بنيتها"""
    engine = create_async_engine(DATABASE_URL)
    async with engine.begin() as conn:
        # TRUNCATE ... RESTART IDENTITY CASCADE: يمسح البيانات ويعيد العدادات
        table_list = ", ".join(TABLES)
        print(f"🗑  تصفير {len(TABLES)} جدول في PostgreSQL...")
        await conn.execute(text(
            f"TRUNCATE TABLE {table_list} RESTART IDENTITY CASCADE;"
        ))
    await engine.dispose()
    print("✅ تم تصفير جداول PostgreSQL.")


def reset_sqlite():
    """حذف كل ملفات SQLite للبوتات المصنوعة"""
    total = 0
    for db_dir in COBOT_DB_DIRS:
        if not os.path.isdir(db_dir):
            continue
        for db_file in glob.glob(os.path.join(db_dir, "*.db")):
            try:
                os.remove(db_file)
                total += 1
            except Exception as e:
                print(f"⚠️ تعذر حذف {db_file}: {e}")
    print(f"✅ تم حذف {total} ملف SQLite للبوتات المصنوعة.")


async def main():
    print("=" * 50)
    print("⚠️  تصفير مشروع KODO Factory بالكامل")
    print("=" * 50)
    print("\nسيتم حذف:")
    print("  • كل المستخدمين والبوتات المصنوعة")
    print("  • كل المدفوعات والاشتراكات والأرصدة")
    print("  • كل الإعدادات والقنوات والإذاعات")
    print("  • كل ملفات SQLite للبوتات المصنوعة")
    print("\n⚠️  هذا الإجراء لا يمكن التراجع عنه!\n")

    confirm = input('للتأكيد اكتب بالضبط: DELETE\n> ').strip()
    if confirm != "DELETE":
        print("❌ تم الإلغاء. لم يُحذف أي شيء.")
        return

    print()
    await reset_postgres()
    reset_sqlite()
    print("\n🎉 اكتمل التصفير. المشروع الآن نظيف كأنك بدأت من جديد.")
    print("ℹ️  أعد تشغيل البوت: python3 kodo.py")


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