#!/usr/bin/env python
"""
Configuration Diagnostic Script for PayTech Integration
Run this on your production server to check if everything is configured correctly
"""

import os
import django
import requests
from django.conf import settings

from appsponsor.models import Donation

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectesm.settings')
django.setup()

def check_config():
    """Check PayTech configuration"""
    print("=" * 60)
    print("🔍 PayTech Configuration Diagnostic")
    print("=" * 60)
    
    issues = []
    warnings = []
    
    # Check API credentials
    print("\n📋 Checking API Credentials...")
    if not settings.PAYTECH_API_KEY or settings.PAYTECH_API_KEY == 'None':
        issues.append("❌ PAYTECH_API_KEY is not set")
    else:
        print(f"✅ PAYTECH_API_KEY: {settings.PAYTECH_API_KEY[:10]}...")
    
    if not settings.PAYTECH_API_SECRET or settings.PAYTECH_API_SECRET == 'None':
        issues.append("❌ PAYTECH_API_SECRET is not set")
    else:
        print(f"✅ PAYTECH_API_SECRET: {settings.PAYTECH_API_SECRET[:10]}...")
    
    # Check environment
    print("\n🌍 Checking Environment...")
    print(f"   PAYTECH_ENV: {settings.PAYTECH_ENV}")
    print(f"   DEBUG: {settings.DEBUG}")
    if settings.DEBUG and settings.PAYTECH_ENV == 'prod':
        warnings.append("⚠️  DEBUG=True with PAYTECH_ENV=prod (not recommended)")
    
    # Check URLs
    print("\n🔗 Checking Callback URLs...")
    print(f"   Base URL: {settings.PAYTECH_BASE_URL}")
    print(f"   Success URL: {settings.PAYTECH_SUCCESS_URL}")
    print(f"   Cancel URL: {settings.PAYTECH_CANCEL_URL}")
    print(f"   IPN URL: {settings.PAYTECH_IPN_URL}")
    
    if not settings.PAYTECH_IPN_URL or settings.PAYTECH_IPN_URL == 'None':
        issues.append("❌ PAYTECH_IPN_URL is not set")
    elif not settings.PAYTECH_IPN_URL.startswith('https://'):
        warnings.append("⚠️  IPN URL should use HTTPS in production")
    
    # Check database connection
    print("\n💾 Checking Database...")
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        print("✅ Database connection OK")
    except Exception as e:
        issues.append(f"❌ Database error: {str(e)}")
    
    # Check if we can import required models
    print("\n📦 Checking Models...")
    try:
        print("✅ Models imported successfully")
        
        # Check if tables exist
        donation_count = Donation.objects.count()
        print(f"   Donations in DB: {donation_count}")
    except Exception as e:
        issues.append(f"❌ Model error: {str(e)}")
    
    # Test PayTech API connectivity (optional)
    print("\n🌐 Testing PayTech API Connectivity...")
    if settings.PAYTECH_API_KEY and settings.PAYTECH_API_SECRET:
        try:
            # Just check if we can reach the API
            test_url = f"{settings.PAYTECH_BASE_URL}/payment/request-payment"
            print(f"   Testing: {test_url}")
            
            # Send a minimal test request (will fail but confirms connectivity)
            headers = {
                'API_KEY': settings.PAYTECH_API_KEY,
                'API_SECRET': settings.PAYTECH_API_SECRET,
                'Content-Type': 'application/json'
            }
            response = requests.post(test_url, json={}, headers=headers, timeout=10)
            print(f"   Response Status: {response.status_code}")
            
            if response.status_code in [200, 400, 422]:
                print("✅ PayTech API is reachable")
                try:
                    resp_json = response.json()
                    if resp_json.get('success') == 0:
                        print(f"   API Response: {resp_json.get('message', 'No message')}")
                except Exception as e:
                    warnings.append(f"⚠️  Error parsing API response: {str(e)}")
            else:
                warnings.append(f"⚠️  Unexpected status code: {response.status_code}")
                
        except requests.exceptions.Timeout:
            warnings.append("⚠️  PayTech API request timed out")
        except requests.exceptions.ConnectionError:
            issues.append("❌ Cannot connect to PayTech API")
        except Exception as e:
            warnings.append(f"⚠️  API test error: {str(e)}")
    else:
        print("   Skipped (API credentials missing)")
    
    # Print summary
    print("\n" + "=" * 60)
    print("📊 SUMMARY")
    print("=" * 60)
    
    if issues:
        print("\n❌ CRITICAL ISSUES:")
        for issue in issues:
            print(f"   {issue}")
    
    if warnings:
        print("\n⚠️  WARNINGS:")
        for warning in warnings:
            print(f"   {warning}")
    
    if not issues and not warnings:
        print("\n✅ All checks passed! Configuration looks good.")
    elif not issues:
        print("\n✅ No critical issues found. Review warnings above.")
    else:
        print("\n❌ Please fix the critical issues above.")
    
    print("\n" + "=" * 60)
    
    return len(issues) == 0

if __name__ == '__main__':
    try:
        success = check_config()
        exit(0 if success else 1)
    except Exception as e:
        print(f"\n❌ Fatal error: {str(e)}")
        import traceback
        traceback.print_exc()
        exit(1)
