#!/usr/bin/env python3
"""
GRNexus CLI - Command Line Interface for GRNexus
Provides easy access to tests and examples
"""

import sys
import os
import subprocess
from pathlib import Path

def get_tests_dir():
    """Get the tests directory path"""
    # Try to find tests directory
    possible_paths = [
        Path(__file__).parent / 'tests',
        Path.cwd() / 'tests',
        Path.cwd() / 'python' / 'tests',
    ]
    
    for path in possible_paths:
        if path.exists():
            return path
    
    return None

def list_tests():
    """List all available tests"""
    tests_dir = get_tests_dir()
    if not tests_dir:
        print("❌ Tests directory not found")
        return []
    
    tests = []
    for category_dir in sorted(tests_dir.iterdir()):
        if category_dir.is_dir() and not category_dir.name.startswith('_'):
            for test_file in sorted(category_dir.glob('test_*.py')):
                test_name = test_file.stem.replace('test_', '')
                category = category_dir.name
                tests.append((category, test_name, test_file))
    
    return tests

def run_test(test_path):
    """Run a specific test file"""
    print(f"\n🚀 Running: {test_path.name}")
    print("=" * 60)
    
    try:
        result = subprocess.run(
            [sys.executable, str(test_path)],
            cwd=test_path.parent,
            check=False
        )
        return result.returncode == 0
    except Exception as e:
        print(f"❌ Error running test: {e}")
        return False

def run_category(category_name):
    """Run all tests in a category"""
    tests_dir = get_tests_dir()
    if not tests_dir:
        print("❌ Tests directory not found")
        return False
    
    category_dir = tests_dir / category_name
    if not category_dir.exists():
        print(f"❌ Category '{category_name}' not found")
        print(f"\nAvailable categories:")
        for cat_dir in sorted(tests_dir.iterdir()):
            if cat_dir.is_dir() and not cat_dir.name.startswith('_'):
                print(f"  - {cat_dir.name}")
        return False
    
    test_files = list(category_dir.glob('test_*.py'))
    if not test_files:
        print(f"❌ No tests found in category '{category_name}'")
        return False
    
    print(f"\n📁 Running all tests in category: {category_name}")
    print(f"   Found {len(test_files)} test(s)")
    print("=" * 60)
    
    passed = 0
    failed = 0
    
    for test_file in sorted(test_files):
        if run_test(test_file):
            passed += 1
        else:
            failed += 1
    
    print("\n" + "=" * 60)
    print(f"✅ Passed: {passed}")
    if failed > 0:
        print(f"❌ Failed: {failed}")
    
    return failed == 0

def run_all_tests():
    """Run all available tests"""
    tests = list_tests()
    if not tests:
        print("❌ No tests found")
        return False
    
    print(f"\n🧪 Running ALL tests ({len(tests)} total)")
    print("=" * 60)
    
    passed = 0
    failed = 0
    
    for category, test_name, test_path in tests:
        print(f"\n[{category}/{test_name}]")
        if run_test(test_path):
            passed += 1
        else:
            failed += 1
    
    print("\n" + "=" * 60)
    print(f"✅ Passed: {passed}/{len(tests)}")
    if failed > 0:
        print(f"❌ Failed: {failed}/{len(tests)}")
    
    return failed == 0

def show_help():
    """Show help message"""
    print("""
🧠 GRNexus CLI - Neural Network Testing Tool

Usage:
  grnexus test                    Run all tests
  grnexus test <category>         Run all tests in a category
  grnexus test <category>/<name>  Run a specific test
  grnexus list                    List all available tests
  grnexus --help                  Show this help message

Examples:
  grnexus test                    # Run all tests
  grnexus test classification     # Run all classification tests
  grnexus test classification/iris  # Run iris test only
  grnexus list                    # Show all available tests

Categories:
  - classification  (Iris, Digits, Sentiment)
  - regression      (Housing)
  - ml_algorithms   (KNN, K-Means, etc.)
  - integration     (Complex architectures)
  - unit            (Core functionality)

For more information: https://github.com/grcodedigitalsolutions/GRNexus
""")

def main():
    """Main CLI entry point"""
    if len(sys.argv) < 2:
        show_help()
        return
    
    command = sys.argv[1].lower()
    
    if command in ['--help', '-h', 'help']:
        show_help()
        return
    
    if command == 'list':
        tests = list_tests()
        if not tests:
            print("❌ No tests found")
            return
        
        print("\n📋 Available Tests:\n")
        current_category = None
        for category, test_name, test_path in tests:
            if category != current_category:
                print(f"\n📁 {category}/")
                current_category = category
            print(f"   - {test_name}")
        print()
        return
    
    if command == 'test':
        if len(sys.argv) < 3:
            # Run all tests
            success = run_all_tests()
            sys.exit(0 if success else 1)
        
        target = sys.argv[2]
        
        # Check if it's category/test format
        if '/' in target:
            category, test_name = target.split('/', 1)
            tests_dir = get_tests_dir()
            if not tests_dir:
                print("❌ Tests directory not found")
                sys.exit(1)
            
            test_file = tests_dir / category / f"test_{test_name}.py"
            if not test_file.exists():
                print(f"❌ Test not found: {target}")
                print(f"\nUse 'grnexus list' to see available tests")
                sys.exit(1)
            
            success = run_test(test_file)
            sys.exit(0 if success else 1)
        else:
            # Assume it's a category
            success = run_category(target)
            sys.exit(0 if success else 1)
    
    print(f"❌ Unknown command: {command}")
    print("Use 'grnexus --help' for usage information")
    sys.exit(1)

if __name__ == '__main__':
    main()
