"""
Test script for the improvements made to markdownconverter.
Tests the new features and enhancements.
"""

import os
import sys
from pathlib import Path

# Add the project root to the path
sys.path.insert(0, str(Path(__file__).parent))

from markdownconverter.utils.error_handler import (
    classify_error, 
    get_user_friendly_message,
    ErrorCategory
)
from markdownconverter.core.core import (
    ConverterNotFoundError,
    TemplatePlaceholderError
)


def test_error_classification():
    """Test that errors are classified correctly."""
    print("Testing error classification...")
    
    # Test FileNotFoundError
    err = FileNotFoundError("test.txt not found")
    category = classify_error(err)
    assert category == ErrorCategory.FILE_NOT_FOUND, f"Expected FILE_NOT_FOUND, got {category}"
    print("✅ FileNotFoundError classified correctly")
    
    # Test TemplatePlaceholderError
    err = TemplatePlaceholderError("Missing placeholder")
    category = classify_error(err)
    assert category == ErrorCategory.TEMPLATE_ERROR, f"Expected TEMPLATE_ERROR, got {category}"
    print("✅ TemplatePlaceholderError classified correctly")
    
    # Test ConverterNotFoundError
    err = ConverterNotFoundError("No converter found")
    category = classify_error(err)
    assert category == ErrorCategory.CONVERTER_MISSING, f"Expected CONVERTER_MISSING, got {category}"
    print("✅ ConverterNotFoundError classified correctly")
    
    # Test PermissionError
    err = PermissionError("Access denied")
    category = classify_error(err)
    assert category == ErrorCategory.PERMISSION_ERROR, f"Expected PERMISSION_ERROR, got {category}"
    print("✅ PermissionError classified correctly")
    
    # Test timeout
    err = RuntimeError("Operation timed out")
    category = classify_error(err)
    assert category == ErrorCategory.TIMEOUT_ERROR, f"Expected TIMEOUT_ERROR, got {category}"
    print("✅ Timeout error classified correctly")
    
    print("\n✅ All error classification tests passed!\n")


def test_user_friendly_messages():
    """Test that user-friendly messages are generated correctly."""
    print("Testing user-friendly messages...")
    
    categories = [
        ErrorCategory.FILE_NOT_FOUND,
        ErrorCategory.TEMPLATE_ERROR,
        ErrorCategory.CONVERTER_MISSING,
        ErrorCategory.CONVERSION_FAILED,
        ErrorCategory.PERMISSION_ERROR,
        ErrorCategory.TIMEOUT_ERROR,
        ErrorCategory.UNKNOWN
    ]
    
    for category in categories:
        err = Exception(f"Test error for {category}")
        title, message = get_user_friendly_message(category, err)
        assert title, f"Title should not be empty for {category}"
        assert message, f"Message should not be empty for {category}"
        assert "Test error" in message, f"Original error should be in message for {category}"
        print(f"✅ {category}: '{title}' message generated")
    
    print("\n✅ All message generation tests passed!\n")


def test_imports():
    """Test that all new imports work correctly."""
    print("Testing imports...")
    
    try:
        from markdownconverter.core.core import (
            combine_markdown_files,
            convert_markdown_to_docx_with_pandoc
        )
        print("✅ Core functions imported successfully")
        
        from markdownconverter.utils.error_handler import (
            handle_conversion_error,
            safe_conversion
        )
        print("✅ Error handler functions imported successfully")
        
        print("\n✅ All imports successful!\n")
        
    except ImportError as e:
        print(f"❌ Import failed: {e}")
        sys.exit(1)


def main():
    print("="*60)
    print("MARKDOWN CONVERTER - IMPROVEMENTS TEST SUITE")
    print("="*60)
    print()
    
    try:
        test_imports()
        test_error_classification()
        test_user_friendly_messages()
        
        print("="*60)
        print("✅ ALL TESTS PASSED!")
        print("="*60)
        print()
        print("Improvements summary:")
        print("1. ✅ nl2br extension added to PDF converter")
        print("2. ✅ Pandoc consolidation with pypandoc")
        print("3. ✅ LibreOffice retry logic implemented")
        print("4. ✅ Unified error handling system created")
        print("5. ✅ Batch converter preview and confirmation")
        print()
        
    except AssertionError as e:
        print(f"\n❌ TEST FAILED: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ UNEXPECTED ERROR: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
