#!/usr/bin/env python3
"""
Test runner for MusicBrainz Data Cleaner.
Run all tests or specific test modules.
"""

import unittest
import sys
import os
from pathlib import Path

# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))


def run_all_tests():
    """Run all tests in the tests directory."""
    # Discover and run all tests
    loader = unittest.TestLoader()
    start_dir = os.path.dirname(__file__)
    suite = loader.discover(start_dir, pattern='test_*.py')
    
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    return result.wasSuccessful()


def run_unit_tests():
    """Run only unit tests."""
    loader = unittest.TestLoader()
    unit_dir = os.path.join(os.path.dirname(__file__), 'unit')
    suite = loader.discover(unit_dir, pattern='test_*.py')
    
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    return result.wasSuccessful()


def run_integration_tests():
    """Run only integration tests."""
    loader = unittest.TestLoader()
    integration_dir = os.path.join(os.path.dirname(__file__), 'integration')
    suite = loader.discover(integration_dir, pattern='test_*.py')
    
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    return result.wasSuccessful()


def run_specific_test(test_module):
    """Run a specific test module."""
    loader = unittest.TestLoader()
    
    # Try to find the test in different directories
    test_dirs = ['', 'unit', 'integration', 'debug']
    suite = None
    
    for test_dir in test_dirs:
        try:
            if test_dir:
                suite = loader.loadTestsFromName(f'tests.{test_dir}.{test_module}')
            else:
                suite = loader.loadTestsFromName(f'tests.{test_module}')
            break
        except:
            continue
    
    if suite is None:
        print(f"❌ Test module '{test_module}' not found")
        return False
    
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    return result.wasSuccessful()


def list_available_tests():
    """List all available test modules."""
    test_dirs = {
        'unit': 'Unit tests for individual components',
        'integration': 'Integration tests for database and API',
        'debug': 'Debug scripts and troubleshooting tests'
    }
    
    print("📋 Available test categories:")
    for test_dir, description in test_dirs.items():
        dir_path = os.path.join(os.path.dirname(__file__), test_dir)
        if os.path.exists(dir_path):
            tests = [f for f in os.listdir(dir_path) if f.startswith('test_') and f.endswith('.py')]
            if tests:
                print(f"\n🔧 {test_dir.upper()} - {description}")
                for test in tests:
                    print(f"  - {test[:-3]}")


if __name__ == '__main__':
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == '--list':
            list_available_tests()
            sys.exit(0)
        elif command == '--unit':
            success = run_unit_tests()
        elif command == '--integration':
            success = run_integration_tests()
        else:
            # Run specific test module
            success = run_specific_test(command)
    else:
        # Run all tests
        print("🧪 Running all tests...")
        success = run_all_tests()
    
    sys.exit(0 if success else 1) 