"""
Test script for Model Manager
Kiểm tra các chức năng: list models, load models, validate models
"""

from model_manager import ModelManager, get_model_manager
import json

def test_model_manager():
    print("="*70)
    print("MODEL MANAGER TEST")
    print("="*70)
    
    # Initialize ModelManager
    model_manager = get_model_manager()
    print("\n✅ ModelManager initialized")
    
    # Test 1: List all models
    print("\n" + "="*70)
    print("TEST 1: LIST ALL MODELS")
    print("="*70)
    
    models = model_manager.list_models()
    print(f"\n📦 Found {len(models)} models:")
    
    for idx, model in enumerate(models, 1):
        print(f"\n[{idx}] {model['filename']}")
        print(f"    Size: {model['size_mb']:.2f} MB")
        print(f"    Modified: {model['modified']}")
        
        if model.get('has_metadata'):
            print(f"    Type: {model.get('model_type', 'N/A')}")
            print(f"    Features: {model.get('n_features', 'N/A')}")
            print(f"    Accuracy: {model.get('test_accuracy', 'N/A')}")
            print(f"    Feature list: {model.get('features', [])}")
        else:
            print(f"    ⚠️  No metadata")
    
    # Test 2: Load a model
    if len(models) > 0:
        print("\n" + "="*70)
        print("TEST 2: LOAD MODEL")
        print("="*70)
        
        test_model = models[0]['filename']
        print(f"\n🔄 Loading model: {test_model}")
        
        try:
            model, encoder, metadata = model_manager.load_model(test_model)
            print(f"✅ Model loaded successfully!")
            print(f"\n📊 Metadata:")
            print(json.dumps(metadata, indent=2))
            
            # Test 3: Validate model
            print("\n" + "="*70)
            print("TEST 3: VALIDATE MODEL")
            print("="*70)
            
            validation = model_manager.validate_model(test_model)
            print(f"\n✅ Validation result:")
            print(f"  Valid: {validation['valid']}")
            if validation['errors']:
                print(f"  Errors: {validation['errors']}")
            if validation['warnings']:
                print(f"  Warnings: {validation['warnings']}")
            
            # Test 4: Get required features
            print("\n" + "="*70)
            print("TEST 4: GET REQUIRED FEATURES")
            print("="*70)
            
            features = model_manager.get_required_features(test_model)
            print(f"\n📋 Required features for {test_model}:")
            for feat in features:
                print(f"  - {feat}")
            
        except Exception as e:
            print(f"❌ Error loading model: {e}")
            import traceback
            traceback.print_exc()
    
    # Test 5: Get latest model
    print("\n" + "="*70)
    print("TEST 5: GET LATEST MODEL")
    print("="*70)
    
    latest = model_manager.get_latest_model()
    print(f"\n📌 Latest model: {latest}")
    
    latest_xgb = model_manager.get_latest_model(model_type='xgboost')
    print(f"📌 Latest XGBoost model: {latest_xgb}")
    
    latest_cnn = model_manager.get_latest_model(model_type='cnn')
    print(f"📌 Latest CNN model: {latest_cnn}")
    
    print("\n" + "="*70)
    print("✅ ALL TESTS COMPLETED")
    print("="*70)

if __name__ == "__main__":
    test_model_manager()
