#!/usr/bin/env python
"""
Debug test to check URL routing
"""
import os
import sys
import django

# Add the project directory to the Python path
sys.path.append('/home/ismail/projects/ats/kaauh_ats')

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

from django.test import Client
from django.urls import reverse
from django.contrib.auth import get_user_model
from recruitment.models import JobPosting, Application, Person

User = get_user_model()

def debug_url_routing():
    """Debug URL routing for document upload"""
    print("Debugging URL routing...")

    # Clean up existing test data
    User.objects.filter(username__startswith='testcandidate').delete()

    # Create test data
    client = Client()

    # Create a test user with unique username
    import uuid
    unique_id = str(uuid.uuid4())[:8]
    user = User.objects.create_user(
        username=f'testcandidate_{unique_id}',
        email=f'test_{unique_id}@example.com',
        password='testpass123',
        user_type='candidate'
    )

    # Create a test job
    from datetime import date, timedelta
    job = JobPosting.objects.create(
        title='Test Job',
        description='Test Description',
        open_positions=1,
        status='ACTIVE',
        application_deadline=date.today() + timedelta(days=30)
    )

    # Create a test person first
    person = Person.objects.create(
        first_name='Test',
        last_name='Candidate',
        email=f'test_{unique_id}@example.com',
        phone='1234567890',
        user=user
    )

    # Create a test application
    application = Application.objects.create(
        job=job,
        person=person
    )

    print(f"Created application with slug: {application.slug}")
    print(f"Application ID: {application.id}")

    # Log in the user
    client.login(username=f'testcandidate_{unique_id}', password='testpass123')

    # Test different URL patterns
    try:
        url1 = reverse('document_upload', kwargs={'slug': application.slug})
        print(f"URL pattern 1 (document_upload): {url1}")
    except Exception as e:
        print(f"Error with document_upload URL: {e}")

    try:
        url2 = reverse('candidate_document_upload', kwargs={'slug': application.slug})
        print(f"URL pattern 2 (candidate_document_upload): {url2}")
    except Exception as e:
        print(f"Error with candidate_document_upload URL: {e}")

    # Test GET request to see if the URL is accessible
    try:
        response = client.get(url1)
        print(f"GET request to {url1}: Status {response.status_code}")
        if response.status_code != 200:
            print(f"Response content: {response.content}")
    except Exception as e:
        print(f"Error making GET request: {e}")

    # Test the second URL pattern
    try:
        response = client.get(url2)
        print(f"GET request to {url2}: Status {response.status_code}")
        if response.status_code != 200:
            print(f"Response content: {response.content}")
    except Exception as e:
        print(f"Error making GET request to {url2}: {e}")

    # Clean up
    application.delete()
    job.delete()
    user.delete()

    print("Debug completed.")

if __name__ == '__main__':
    debug_url_routing()
