#!/usr/bin/env python
"""
Diagnostic script to check if M-Pesa templates exist on the server
Run this on the production server to verify template files
"""

import os
import sys

# Add the project directory to the path
sys.path.insert(0, '/home/acbptxvs/public_html/branchbusinessadvance.co.ke')

# Set Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')

try:
    import django
    django.setup()
    from django.conf import settings
    
    print("="*70)
    print("TEMPLATE DIRECTORY DIAGNOSTIC")
    print("="*70)
    
    # Get BASE_DIR
    base_dir = settings.BASE_DIR
    print(f"\nBASE_DIR: {base_dir}")
    
    # Get template directories
    template_dirs = settings.TEMPLATES[0]['DIRS']
    print(f"\nTemplate DIRS: {template_dirs}")
    
    # Check if templates directory exists
    templates_dir = os.path.join(base_dir, 'templates')
    print(f"\nChecking: {templates_dir}")
    print(f"Exists: {os.path.exists(templates_dir)}")
    
    if os.path.exists(templates_dir):
        print(f"Is directory: {os.path.isdir(templates_dir)}")
        print(f"Permissions: {oct(os.stat(templates_dir).st_mode)[-3:]}")
    
    # Check payments subdirectory
    payments_dir = os.path.join(templates_dir, 'payments')
    print(f"\nChecking: {payments_dir}")
    print(f"Exists: {os.path.exists(payments_dir)}")
    
    if os.path.exists(payments_dir):
        print(f"Is directory: {os.path.isdir(payments_dir)}")
        print(f"Permissions: {oct(os.stat(payments_dir).st_mode)[-3:]}")
        
        # List all files in payments directory
        print(f"\nFiles in {payments_dir}:")
        try:
            files = os.listdir(payments_dir)
            for f in sorted(files):
                file_path = os.path.join(payments_dir, f)
                if os.path.isfile(file_path):
                    size = os.path.getsize(file_path)
                    perms = oct(os.stat(file_path).st_mode)[-3:]
                    print(f"  - {f} ({size} bytes, perms: {perms})")
        except Exception as e:
            print(f"  Error listing files: {e}")
    
    # Check specific required templates
    print("\n" + "="*70)
    print("REQUIRED TEMPLATE FILES")
    print("="*70)
    
    required_templates = [
        'callbacks.html',
        'transaction_detail.html',
        'reprocess_transaction.html',
        'my_payments.html',
        'dashboard.html',
        'transactions.html',
        'configuration.html',
        'test_payment.html',
    ]
    
    missing = []
    for template in required_templates:
        template_path = os.path.join(payments_dir, template)
        exists = os.path.exists(template_path)
        status = "✓ EXISTS" if exists else "✗ MISSING"
        
        if exists:
            size = os.path.getsize(template_path)
            perms = oct(os.stat(template_path).st_mode)[-3:]
            print(f"{status} - {template} ({size} bytes, perms: {perms})")
        else:
            print(f"{status} - {template}")
            missing.append(template)
    
    # Summary
    print("\n" + "="*70)
    print("SUMMARY")
    print("="*70)
    
    if missing:
        print(f"\n✗ {len(missing)} template(s) MISSING:")
        for t in missing:
            print(f"  - {t}")
        print("\nAction Required:")
        print("1. Upload missing templates to:")
        print(f"   {payments_dir}/")
        print("2. Set file permissions to 644:")
        print(f"   chmod 644 {payments_dir}/*.html")
        print("3. Restart the application")
    else:
        print("\n✓ All required templates are present!")
        print("\nIf you're still getting TemplateDoesNotExist error:")
        print("1. Restart the application:")
        print("   touch /home/acbptxvs/public_html/branchbusinessadvance.co.ke/passenger_wsgi.py")
        print("2. Clear browser cache")
        print("3. Check Django logs for other errors")
    
    print("\n")

except Exception as e:
    print(f"\nError: {e}")
    import traceback
    traceback.print_exc()
