#!/usr/bin/env python
"""
Script to run the test suite for ARCH application.
Executes all tests and generates JSON and HTML reports.
"""
import pytest
import os
import sys
import argparse
import json
import shutil
from datetime import datetime

def run_tests(args):
    """Run pytest with specified arguments and generate reports."""
    # Create test reports directory if needed
    os.makedirs('test_reports', exist_ok=True)
    
    # Generate timestamp for report files
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    
    # Base pytest arguments
    pytest_args = [
        '-v',                                      # Verbose output
        '--no-header',                             # No header in the output
        '--tb=short',                              # Short traceback
        f'--junitxml=test_reports/junit_{timestamp}.xml',  # JUnit XML report
        '--cov=app',                               # Coverage for app module
        '--cov=routes',                            # Coverage for routes
        '--cov=services',                          # Coverage for services
        '--cov=utils',                             # Coverage for utils
        '--cov-report=html:test_reports/coverage', # HTML coverage report
    ]
    
    # Add test files/directories
    if args.tests:
        pytest_args.extend(args.tests)
    else:
        pytest_args.append('tests/')
    
    # Execute tests
    print(f"\n{'='*80}")
    print(f"Running tests at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'='*80}")
    
    result = pytest.main(pytest_args)
    
    # Generate JSON report
    print(f"\n{'='*80}")
    print(f"Test report available at: test_reports/test_results_{timestamp}.json")
    print(f"Coverage report available at: test_reports/coverage/index.html")
    print(f"{'='*80}\n")
    
    return result

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run tests for ARCH application")
    parser.add_argument('tests', nargs='*', help='Specific test files or directories to run')
    parser.add_argument('--clean', action='store_true', help='Clean test storage and results before running')
    
    args = parser.parse_args()
    
    if args.clean:
        # Clean temporary test storage
        if os.path.exists('test_storage'):
            shutil.rmtree('test_storage')
        # Clean previous test reports
        if os.path.exists('test_reports'):
            shutil.rmtree('test_reports')
        print("Cleaned test storage and reports.")
    
    # Run tests and exit with the pytest result code
    sys.exit(run_tests(args))
