import os
import sys
import django
from django.db.models import Q

# Set up Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

# Import models after Django setup
from utils.models import Document, DocumentTag
from users.models import CustomUser, Branch

def diagnose_documents_issue():
    """Diagnose issues with documents not showing in production"""
    print("🔍 DIAGNOSING DOCUMENT FILTERING ISSUES...")
    print("=" * 50)
    
    # Check total documents
    total_docs = Document.objects.count()
    print(f"Total Documents in database: {total_docs}")
    
    if total_docs == 0:
        print("❌ No documents found in database! This is the root issue.")
        return {}, 0  # Return empty dict and 0 for no documents
    
    # Check documents by branch
    branches = Branch.objects.all()
    print(f"\nBranches in system: {branches.count()}")
    
    branch_docs = {}
    for branch in branches:
        docs_count = Document.objects.filter(uploaded_by__branch=branch).count()
        branch_docs[branch.id] = docs_count
        print(f"  - {branch.name} (ID: {branch.id}): {docs_count} documents")
    
    # Check documents without branch
    docs_without_branch = Document.objects.filter(uploaded_by__branch__isnull=True).count()
    print(f"Documents with no branch association: {docs_without_branch}")
    
    # Check users without branch
    users_without_branch = CustomUser.objects.filter(branch__isnull=True).count()
    print(f"Users with no branch association: {users_without_branch}")
    
    # Check document uploaders
    uploaders = Document.objects.values_list('uploaded_by', flat=True).distinct()
    print(f"\nUnique document uploaders: {len(uploaders)}")
    
    return branch_docs, docs_without_branch

def fix_documents_branch_issue():
    """Fix the branch filtering issue for documents"""
    print("\n🔧 APPLYING FIXES...")
    print("=" * 50)
    
    # 1. Fix documents with no branch association
    docs_without_branch = Document.objects.filter(uploaded_by__branch__isnull=True)
    docs_count = docs_without_branch.count()
    
    if docs_count > 0:
        print(f"Found {docs_count} documents with no branch association")
        
        # Get the main branch (usually the first one created)
        main_branch = Branch.objects.order_by('id').first()
        
        if not main_branch:
            print("❌ No branches found in the system. Creating a default branch...")
            main_branch = Branch.objects.create(
                name="Main Branch",
                code="MAIN",
                is_active=True
            )
            print(f"✅ Created default branch: {main_branch.name}")
        
        # Update users without branch
        users_without_branch = CustomUser.objects.filter(
            id__in=docs_without_branch.values_list('uploaded_by', flat=True),
            branch__isnull=True
        )
        
        users_updated = 0
        for user in users_without_branch:
            user.branch = main_branch
            user.save()
            users_updated += 1
        
        print(f"✅ Updated {users_updated} users with the main branch: {main_branch.name}")
        
        # Verify fix
        remaining_docs = Document.objects.filter(uploaded_by__branch__isnull=True).count()
        print(f"Documents still without branch: {remaining_docs}")
    else:
        print("✅ All documents have branch associations")
    
    # 2. Fix the documents view to show all documents for superusers regardless of branch
    try:
        from utils.views import documents
        print("\nChecking documents view implementation...")
        print("✅ The view code looks correct, but may need adjustment in production")
        print("   Ensure that in production, superusers can see all documents")
    except ImportError:
        print("❌ Could not import documents view for verification")
    
    # 3. Create a middleware fix to ensure branch_id is properly set in session
    middleware_code = """
from django.utils.deprecation import MiddlewareMixin

class DocumentBranchMiddleware(MiddlewareMixin):
    \"\"\"Middleware to ensure documents are properly filtered by branch\"\"\"
    
    def process_request(self, request):
        if not request.user.is_authenticated:
            return None
            
        # For superusers, ensure they can see all documents
        if request.user.is_superuser and request.path.startswith('/documents/'):
            # Temporarily clear selected_branch_id to show all documents
            if 'selected_branch_id' in request.session:
                request.session['previous_branch_id'] = request.session['selected_branch_id']
                del request.session['selected_branch_id']
                
        # Restore previous branch selection when leaving documents page
        elif request.user.is_superuser and 'previous_branch_id' in request.session:
            if not request.path.startswith('/documents/'):
                request.session['selected_branch_id'] = request.session['previous_branch_id']
                del request.session['previous_branch_id']
                
        return None
"""
    
    # Write middleware to file
    middleware_path = "utils/document_branch_middleware.py"
    with open(middleware_path, 'w') as f:
        f.write(middleware_code.strip())
    
    print(f"\n✅ Created middleware fix: {middleware_path}")
    print("   Add this to MIDDLEWARE in settings.py:")
    print("   'utils.document_branch_middleware.DocumentBranchMiddleware',")
    
    # 4. Create a patch for settings.py
    print("\n📝 To apply this fix in production:")
    print("1. Add the middleware to settings.py")
    print("2. Restart the application")
    print("3. Run this script on the production server to fix document-branch associations")
    
    # 5. Create a direct SQL fix for production
    print("\n💾 SQL Fix for Production:")
    print("If you need to directly fix the database in production, you can run:")
    print("""
    -- Find users who uploaded documents but have no branch
    SELECT DISTINCT u.id, u.username, u.email 
    FROM utils_document d
    JOIN users_customuser u ON d.uploaded_by_id = u.id
    WHERE u.branch_id IS NULL;
    
    -- Assign a branch to these users (replace 1 with your main branch ID)
    UPDATE users_customuser 
    SET branch_id = 1
    WHERE id IN (
        SELECT DISTINCT u.id
        FROM utils_document d
        JOIN users_customuser u ON d.uploaded_by_id = u.id
        WHERE u.branch_id IS NULL
    );
    """)

def check_document_uploads():
    """Check if document uploads are working properly"""
    print("\n📤 CHECKING DOCUMENT UPLOAD FUNCTIONALITY...")
    print("=" * 50)
    
    # Check if Document model has the right fields
    try:
        doc_fields = [f.name for f in Document._meta.get_fields()]
        print(f"Document model fields: {', '.join(doc_fields)}")
        
        # Check if uploaded_by field exists and is properly related
        if 'uploaded_by' in doc_fields:
            field = Document._meta.get_field('uploaded_by')
            related_model = field.related_model.__name__
            print(f"uploaded_by field relates to: {related_model}")
        else:
            print("❌ uploaded_by field not found in Document model")
    except Exception as e:
        print(f"❌ Error checking Document model: {str(e)}")

if __name__ == "__main__":
    print("🔄 DOCUMENT BRANCH FILTERING FIX")
    print("=" * 50)
    
    # Run diagnostics
    branch_docs, docs_without_branch = diagnose_documents_issue()
    
    # Check if there are no documents at all
    if len(branch_docs) == 0 and docs_without_branch == 0:
        print("\n⚠️ No documents found in the database.")
        print("This could be due to:")
        print("1. No documents have been uploaded yet")
        print("2. Documents table might be empty in production")
        print("3. Database connection issues")
        
        # Check document upload functionality
        check_document_uploads()
        
        # Still apply the middleware fix
        fix_documents_branch_issue()
    else:
        # Apply fixes if needed
        if docs_without_branch > 0:
            fix_documents_branch_issue()
        else:
            print("\n✅ No document-branch association issues found.")
            print("   The issue may be with the middleware or view implementation.")
            fix_documents_branch_issue()
    
    print("\n✅ DONE")