# -*- coding: utf-8 -*-
"""Test if model can be loaded"""
import pickle
from pathlib import Path

print("Testing model loading...")
print()

# Find model file
tests_dir = Path(__file__).parent
model_path = tests_dir / 'ml_output' / 'lightweight_model.pkl'

print(f"Tests directory: {tests_dir}")
print(f"Model path: {model_path}")
print(f"Model exists: {model_path.exists()}")
print()

if model_path.exists():
    try:
        with open(model_path, 'rb') as f:
            model_data = pickle.load(f)

        print("SUCCESS! Model loaded")
        print(f"Keys in model_data: {model_data.keys()}")
        print(f"Label map: {model_data.get('label_map')}")
        print(f"Test accuracy: {model_data.get('metadata', {}).get('test_accuracy')}")
        print()

        # Test prediction
        from sklearn.feature_extraction.text import TfidfVectorizer

        vectorizer = model_data['vectorizer']
        model = model_data['model']
        reverse_label_map = model_data['reverse_label_map']

        test_text = "推进一下这个事"
        features = vectorizer.transform([test_text])
        prediction = model.predict(features)[0]
        scenario = reverse_label_map[prediction]

        print(f"Test prediction for '{test_text}': {scenario}")
        print()

    except Exception as e:
        print(f"ERROR loading model: {e}")
        import traceback
        traceback.print_exc()
else:
    print("ERROR: Model file not found!")

print("Checking paths from analyzer...")
# Check the path that analyzer would use
analyzer_file = tests_dir.parent / 'mcp_server' / 'analyzers' / 'lightweight_hybrid_recognizer.py'
print(f"Analyzer file: {analyzer_file}")

# Simulate the path calculation
if analyzer_file.exists():
    tests_dir_from_analyzer = analyzer_file.parent.parent.parent / 'tests'
    ml_model_path_from_analyzer = tests_dir_from_analyzer / 'ml_output' / 'lightweight_model.pkl'

    print(f"Tests dir (from analyzer): {tests_dir_from_analyzer}")
    print(f"Model path (from analyzer): {ml_model_path_from_analyzer}")
    print(f"Model exists (from analyzer): {ml_model_path_from_analyzer.exists()}")

input("\nPress Enter to exit...")
