#!/usr/bin/env python3
"""
retry_failed.py — أعد محاولة الطلبات الفاشلة
الاستخدام:
    python retry_failed.py           # كل الطلبات الفاشلة
    python retry_failed.py 9999      # طلب محدد بـ woo_order_id
"""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app.database.db import init_db, get_connection
from app.models.order import Order
from app.services.recharge_service import process_order
from app.services.order_service import update_order_status
from app.utils.logger import get_logger

logger = get_logger("retry")


def get_failed_orders():
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                "SELECT * FROM orders WHERE status='failed' ORDER BY created_at ASC"
            )
            return [Order.from_row(r) for r in cur.fetchall()]
    finally:
        conn.close()


def retry_order(order: Order):
    logger.info(f"Retrying order #{order.woo_order_id}")
    update_order_status(order.id, "pending")
    success = process_order(order)
    icon = "✅ نجح" if success else "❌ فشل"
    print(f"  {icon}  →  #{order.woo_order_id} | {order.product_name}")


def main():
    init_db()
    if len(sys.argv) > 1:
        woo_id = sys.argv[1]
        conn = get_connection()
        with conn.cursor() as cur:
            cur.execute("SELECT * FROM orders WHERE woo_order_id=%s", (woo_id,))
            row = cur.fetchone()
        conn.close()
        if not row:
            print(f"❌ الطلب #{woo_id} غير موجود.")
            sys.exit(1)
        retry_order(Order.from_row(row))
    else:
        orders = get_failed_orders()
        if not orders:
            print("✅ لا توجد طلبات فاشلة.")
            return
        print(f"🔁 إعادة محاولة {len(orders)} طلب...\n")
        for o in orders:
            retry_order(o)
    print("\nاكتمل.")

if __name__ == "__main__":
    main()
