"""
Quick PayTech Test Script
Run from Django shell: python manage.py shell < test_paytech.py
Or copy-paste into: python manage.py shell
"""

print("=" * 60)
print("🧪 Testing PayTech Integration")
print("=" * 60)

# Import required modules
from django.conf import settings
from appsponsor.paytech_service import PaytechService
import time

# Step 1: Check configuration
print("\n1️⃣ Checking Configuration...")
print(f"   API Key: {settings.PAYTECH_API_KEY[:20] if settings.PAYTECH_API_KEY else 'NOT SET'}...")
print(f"   API Secret: {settings.PAYTECH_API_SECRET[:20] if settings.PAYTECH_API_SECRET else 'NOT SET'}...")
print(f"   Environment: {settings.PAYTECH_ENV}")
print(f"   Base URL: {settings.PAYTECH_BASE_URL}")
print(f"   IPN URL: {settings.PAYTECH_IPN_URL}")

if not settings.PAYTECH_API_KEY or not settings.PAYTECH_API_SECRET:
    print("\n❌ ERROR: PayTech credentials not configured!")
    print("   Please set PAYTECH_API_KEY and PAYTECH_API_SECRET in .env file")
    exit(1)

# Step 2: Initialize service
print("\n2️⃣ Initializing PayTech Service...")
try:
    service = PaytechService()
    print("   ✅ Service initialized successfully")
except Exception as e:
    print(f"   ❌ Failed to initialize: {e}")
    exit(1)

# Step 3: Create test payment request
print("\n3️⃣ Creating Test Payment Request...")
print("   Amount: 1,000 XOF")
print("   Method: Orange Money")

try:
    ref_command = f"TEST_{int(time.time())}"
    
    response = service.request_payment(
        item_name="Test Donation - ONG ESM",
        item_price=1000,
        ref_command=ref_command,
        command_name="Test payment for Enfants Soleil Monde",
        custom_field={
            'test': True,
            'type': 'donation'
        },
        target_payment="Orange Money"
    )
    
    print(f"\n   📋 Response:")
    print(f"   Success: {response.get('success')}")
    print(f"   Token: {response.get('token', 'N/A')}")
    print(f"   Redirect URL: {response.get('redirect_url', 'N/A')[:60]}...")
    
    if response.get('success') == 1:
        print("\n   ✅ TEST PASSED! PayTech integration is working!")
        print(f"\n   🔗 Payment URL: {response.get('redirect_url')}")
        print("\n   Note: This is a real payment link. Don't complete the payment unless testing.")
    else:
        print(f"\n   ❌ TEST FAILED!")
        print(f"   Error: {response.get('message', 'Unknown error')}")
        
        # Common error explanations
        if 'API_KEY' in str(response.get('message', '')):
            print("\n   💡 This usually means:")
            print("      - API credentials are incorrect")
            print("      - Check PAYTECH_API_KEY and PAYTECH_API_SECRET in .env")
        elif 'IPN' in str(response.get('message', '')):
            print("\n   💡 This usually means:")
            print("      - IPN URL is not accessible")
            print("      - Make sure PAYTECH_IPN_URL is HTTPS and publicly accessible")
        
except Exception as e:
    print(f"\n   ❌ ERROR: {type(e).__name__}: {str(e)}")
    import traceback
    print("\n   Stack trace:")
    traceback.print_exc()

print("\n" + "=" * 60)
print("Test complete!")
print("=" * 60)
