"""
Verification script for deleted loans page exclusivity (Property 15)

This script verifies that the deleted_loans view correctly implements
Requirement 5.5: showing ONLY deleted loans (is_deleted=True) and
ensuring no active loans appear on the page.
"""

import os
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from django.db.models import Q

def verify_deleted_loans_exclusivity():
    """
    Verify Property 15: Deleted loans page exclusivity
    
    Requirements 5.5: WHERE a deleted loans page exists THEN the System SHALL
    display only loans where is_deleted equals true
    """
    print("\n" + "="*80)
    print("VERIFICATION: Property 15 - Deleted Loans Page Exclusivity")
    print("="*80)
    print("\nRequirement 5.5: Deleted loans page should show ONLY deleted loans")
    print("-"*80)
    
    # Get all loans
    all_loans = Loan.objects.all()
    print(f"\n📊 Database Statistics:")
    print(f"  Total loans in database: {all_loans.count()}")
    
    # Get deleted loans (what the view shows)
    deleted_loans = Loan.objects.filter(is_deleted=True)
    print(f"  Deleted loans (is_deleted=True): {deleted_loans.count()}")
    
    # Get active loans (should NOT appear on deleted loans page)
    active_loans = Loan.objects.filter(is_deleted=False)
    print(f"  Active loans (is_deleted=False): {active_loans.count()}")
    
    # Verify the view logic
    print(f"\n🔍 Verifying View Logic:")
    print(f"  The deleted_loans view uses: Loan.objects.filter(is_deleted=True)")
    
    # Property 1: All loans in deleted_loans queryset should have is_deleted=True
    print(f"\n✓ Property 1: All returned loans should have is_deleted=True")
    violations = []
    for loan in deleted_loans:
        if not loan.is_deleted:
            violations.append(loan.loan_number)
    
    if violations:
        print(f"  ❌ FAIL: Found {len(violations)} loans with is_deleted=False")
        print(f"  Violating loans: {', '.join(violations)}")
    else:
        print(f"  ✅ PASS: All {deleted_loans.count()} loans have is_deleted=True")
    
    # Property 2: No active loans should appear in deleted_loans queryset
    print(f"\n✓ Property 2: No active loans should appear in results")
    active_in_deleted = deleted_loans.filter(is_deleted=False).count()
    
    if active_in_deleted > 0:
        print(f"  ❌ FAIL: Found {active_in_deleted} active loans in deleted loans queryset")
    else:
        print(f"  ✅ PASS: No active loans in deleted loans queryset")
    
    # Property 3: Verify inverse - active loans should not include deleted loans
    print(f"\n✓ Property 3: Active loans should not include deleted loans")
    deleted_in_active = active_loans.filter(is_deleted=True).count()
    
    if deleted_in_active > 0:
        print(f"  ❌ FAIL: Found {deleted_in_active} deleted loans in active loans queryset")
    else:
        print(f"  ✅ PASS: No deleted loans in active loans queryset")
    
    # Property 4: Verify exclusivity (no overlap)
    print(f"\n✓ Property 4: Verify exclusivity (no overlap between sets)")
    deleted_ids = set(deleted_loans.values_list('id', flat=True))
    active_ids = set(active_loans.values_list('id', flat=True))
    overlap = deleted_ids.intersection(active_ids)
    
    if overlap:
        print(f"  ❌ FAIL: Found {len(overlap)} loans in both sets")
    else:
        print(f"  ✅ PASS: No overlap between deleted and active loans")
    
    # Property 5: Verify completeness (all loans accounted for)
    print(f"\n✓ Property 5: Verify completeness (all loans accounted for)")
    total_accounted = deleted_loans.count() + active_loans.count()
    
    if total_accounted == all_loans.count():
        print(f"  ✅ PASS: All {all_loans.count()} loans accounted for")
        print(f"    - Deleted: {deleted_loans.count()}")
        print(f"    - Active: {active_loans.count()}")
    else:
        print(f"  ❌ FAIL: Mismatch in loan counts")
        print(f"    - Total: {all_loans.count()}")
        print(f"    - Accounted: {total_accounted}")
    
    # Summary
    print("\n" + "="*80)
    all_passed = (
        len(violations) == 0 and
        active_in_deleted == 0 and
        deleted_in_active == 0 and
        len(overlap) == 0 and
        total_accounted == all_loans.count()
    )
    
    if all_passed:
        print("✅ ALL PROPERTIES VERIFIED - IMPLEMENTATION CORRECT")
        print("="*80)
        print("\nSummary:")
        print("  ✓ Deleted loans page shows ONLY deleted loans (is_deleted=True)")
        print("  ✓ No active loans appear on deleted loans page")
        print("  ✓ No deleted loans appear on active loans pages")
        print("  ✓ Complete separation between deleted and active loans")
        print("  ✓ All loans properly accounted for")
        print("\n✅ Requirement 5.5 is satisfied")
    else:
        print("❌ SOME PROPERTIES FAILED - REVIEW IMPLEMENTATION")
    
    print("="*80 + "\n")
    
    return all_passed

if __name__ == '__main__':
    try:
        result = verify_deleted_loans_exclusivity()
        exit(0 if result else 1)
    except Exception as e:
        print(f"\n❌ Error during verification: {str(e)}")
        import traceback
        traceback.print_exc()
        exit(1)
