#!/usr/bin/env python
"""
Test script to verify the staff hierarchy API fix.
This script tests the hierarchy endpoint directly using Django's test framework.
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PX360.settings')
django.setup()

from apps.organizations.models import Staff
from apps.organizations.views import StaffViewSet

def test_hierarchy():
    """Test the hierarchy endpoint"""
    print("Testing Staff Hierarchy API...")
    print("-" * 60)
    
    # Get all staff
    staff_queryset = Staff.objects.all()
    total_staff = staff_queryset.count()
    print(f"Total staff in database: {total_staff}")
    
    if total_staff == 0:
        print("\n⚠️  No staff data found!")
        print("Please import staff data first using:")
        print("  python manage.py import_staff_csv sample_staff_data.csv")
        return
    
    # Get staff with managers
    staff_list = staff_queryset.select_related('report_to', 'hospital', 'department')
    
    # Find root nodes (staff with no manager or manager not in the filtered set)
    staff_dict = {staff.id: staff for staff in staff_list}
    root_staff = [
        staff for staff in staff_list 
        if staff.report_to_id is None or staff.report_to_id not in staff_dict
    ]
    
    print(f"Root nodes (top-level managers): {len(root_staff)}")
    print()
    
    # Show root staff details
    print("Top-Level Managers:")
    for i, staff in enumerate(root_staff[:5], 1):
        print(f"  {i}. {staff.get_full_name()} ({staff.job_title or 'No title'})")
        print(f"     ID: {staff.id}, Employee ID: {staff.employee_id}")
        if len(root_staff) > 5 and i == 5:
            print(f"  ... and {len(root_staff) - 5} more")
            break
    
    print()
    
    # Check if there are multiple root nodes
    if len(root_staff) > 1:
        print("✅ Multiple root nodes detected - Virtual root node will be created")
        print(f"   The API will return a single tree with {len(root_staff)} top-level children")
    elif len(root_staff) == 1:
        print("ℹ️  Single root node detected - No virtual root needed")
        print("   The API will return the single hierarchy tree directly")
    else:
        print("⚠️  No root nodes found - All staff have managers")
    
    print()
    print("-" * 60)
    print("Test completed!")
    print()
    print("To view the hierarchy visualization:")
    print("1. Start the server: python manage.py runserver")
    print("2. Login to the application")
    print("3. Navigate to Organizations > Staff > Hierarchy")

if __name__ == '__main__':
    test_hierarchy()
