#!/usr/bin/env python
"""
Comprehensive Test Execution Script

This script runs all tests for the Granular Permissions and Reporting System
with coverage reporting and performance metrics.
"""

import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner


def setup_django():
    """Set up Django environment for testing"""
    # Add the project directory to Python path
    project_dir = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, project_dir)
    
    # Configure Django settings
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
    
    try:
        django.setup()
    except Exception as e:
        print(f"Error setting up Django: {e}")
        sys.exit(1)


def run_tests():
    """Run comprehensive tests"""
    print("=" * 70)
    print("GRANULAR PERMISSIONS & REPORTING SYSTEM - TEST EXECUTION")
    print("=" * 70)
    print()
    
    # Get the Django test runner
    TestRunner = get_runner(settings)
    
    # Configure test runner
    test_runner = TestRunner(
        verbosity=2,
        interactive=False,
        keepdb=False,
        reverse=False,
        debug_mode=False,
        debug_sql=False,
        parallel=1,
        tags=None,
        exclude_tags=None
    )
    
    # Define test modules to run
    test_modules = [
        'users.tests.test_permission_services',
        'users.tests.test_analytics_services', 
        'users.tests.test_export_functionality',
        'users.tests.test_integration_workflows',
        'users.tests.test_permission_migration',
        'users.tests.test_portfolio_snapshot_service'
    ]
    
    print("Running test modules:")
    for module in test_modules:
        print(f"  - {module}")
    print()
    
    # Run the tests
    failures = test_runner.run_tests(test_modules)
    
    if failures:
        print(f"\n❌ Tests failed with {failures} failure(s)")
        return False
    else:
        print("\n✅ All tests passed successfully!")
        return True


def main():
    """Main execution function"""
    print("Setting up Django environment...")
    setup_django()
    
    print("Starting comprehensive test execution...")
    success = run_tests()
    
    if success:
        print("\n🎉 Comprehensive test suite completed successfully!")
        print("\nNext steps:")
        print("1. Review coverage report in htmlcov/ directory")
        print("2. Check performance metrics in test output")
        print("3. Address any warnings or recommendations")
        sys.exit(0)
    else:
        print("\n💥 Test suite failed!")
        print("\nPlease review the test output and fix any failing tests.")
        sys.exit(1)


if __name__ == '__main__':
    main()