#!/usr/bin/env python3
"""test_system.py — اختبار النظام كاملاً مع MySQL"""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app.database.db import init_db
from app.services.order_service import create_order, get_order_by_woo_id
from app.services.queue_service import enqueue_order, queue_size
from app.models.order import Order
from app.utils.logger import get_logger

logger = get_logger("test")


def test_db():
    print("\n[1] اختبار الاتصال بـ MySQL...")
    try:
        init_db()
        print("    ✅ MySQL متصل والجداول جاهزة")
    except Exception as e:
        print(f"    ❌ فشل الاتصال: {e}")
        print("       تأكد من بيانات DB في .env")
        sys.exit(1)


def test_create_order():
    print("\n[2] اختبار إنشاء طلب...")
    order = Order(
        woo_order_id  = "TEST-MYSQL-001",
        product_name  = "Mobile Legends",
        game_id       = "123456789",
        zone_id       = "1001",
        amount        = 10.0,
        currency      = "USD",
        customer_email= "test@example.com",
        customer_name = "Test User",
    )
    saved = create_order(order)
    if saved and saved.id:
        print(f"    ✅ Order created: ID={saved.id}")
        return saved
    else:
        print("    ❌ فشل إنشاء الطلب!")
        return None


def test_fetch_order():
    print("\n[3] اختبار استرجاع الطلب...")
    o = get_order_by_woo_id("TEST-MYSQL-001")
    if o:
        print(f"    ✅ Order fetched: {o.woo_order_id} | {o.status}")
    else:
        print("    ❌ الطلب غير موجود!")


def test_queue(order):
    print("\n[4] اختبار Queue...")
    if order:
        enqueue_order(order.id)
        print(f"    ✅ Queued. Size={queue_size()}")
    else:
        print("    ⚠️  تخطي — لا يوجد طلب")


def test_telegram():
    print("\n[5] اختبار Telegram...")
    from app.config.settings import TELEGRAM_BOT_TOKEN, ADMIN_CHAT_ID
    if not TELEGRAM_BOT_TOKEN or TELEGRAM_BOT_TOKEN == "your_bot_token_here":
        print("    ⚠️  TELEGRAM_BOT_TOKEN غير مضبوط — تخطي")
        return
    from app.bot.bot import send_result_notification
    order = Order(
        woo_order_id="TEST-MYSQL-001", product_name="Mobile Legends",
        game_id="123456789", amount=10.0, currency="USD",
        customer_name="Test User", result="اختبار ناجح",
    )
    ok = send_result_notification(order, success=True)
    print("    ✅ إشعار أُرسل!" if ok else "    ❌ فشل الإرسال")


def test_api():
    print("\n[6] اختبار Flask API...")
    import requests
    from app.config.settings import API_PORT
    try:
        r = requests.get(f"http://127.0.0.1:{API_PORT}/api/health", timeout=3)
        print(f"    ✅ API يعمل: {r.json()}")
    except Exception as e:
        print(f"    ⚠️  API غير متاح (شغّل run.py أولاً): {e}")


def test_webhook_sim():
    print("\n[7] محاكاة WooCommerce Webhook...")
    import requests, json, hmac, hashlib, base64
    from app.config.settings import API_PORT, WC_WEBHOOK_SECRET
    payload = {
        "id": 88888, "status": "processing",
        "currency": "USD",
        "billing": {"first_name": "أحمد", "last_name": "علي", "email": "ahmed@test.com"},
        "line_items": [{
            "name": "Mobile Legends — 100 Diamonds",
            "total": "5.00",
            "meta_data": [
                {"key": "game_player_id", "value": "987654321"},
                {"key": "game_zone_id",   "value": "1002"},
            ]
        }],
        "meta_data": []
    }
    body = json.dumps(payload).encode()
    sig = ""
    if WC_WEBHOOK_SECRET and WC_WEBHOOK_SECRET != "your_webhook_secret":
        sig = base64.b64encode(
            hmac.new(WC_WEBHOOK_SECRET.encode(), body, hashlib.sha256).digest()
        ).decode()
    try:
        r = requests.post(
            f"http://127.0.0.1:{API_PORT}/api/webhook/woocommerce",
            data=body,
            headers={"Content-Type": "application/json",
                     "X-WC-Webhook-Signature": sig},
            timeout=5,
        )
        print(f"    Response {r.status_code}: {r.json()}")
        print("    ✅ Webhook OK!" if r.status_code == 200 else "    ❌ Webhook فشل")
    except Exception as e:
        print(f"    ⚠️  API غير متاح: {e}")


if __name__ == "__main__":
    print("=" * 50)
    print("  Game Top-up Bot — System Test (MySQL)")
    print("=" * 50)
    test_db()
    order = test_create_order()
    test_fetch_order()
    test_queue(order)
    test_telegram()
    test_api()
    test_webhook_sim()
    print("\n" + "=" * 50)
    print("  اكتمل الاختبار ✅")
    print("=" * 50)
