"""
Functional tests for docdiff module.
This script tests the actual functionality with real .docx files.
"""

import os
import sys
import tempfile
from pathlib import Path

# Add the project root to the path so we can import the module
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from sfi.docdiff.docdiff import DiffDocCommand, DocDiffConfig


def test_basic_functionality():
    """Test basic functionality of docdiff with sample files."""
    print("Testing basic docdiff functionality...")

    # First, let's check if we're on Windows and have Word available
    import platform

    if platform.system() != "Windows":
        print(
            "Skipping functional test: docdiff only works on Windows with Word installed"
        )
        return

    try:
        import win32com.client
    except ImportError:
        print("Skipping functional test: win32com.client not available")
        return
    except Exception:
        print("Skipping functional test: win32com import error")
        return

    # Create temporary files for testing
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)

        # Create simple text files as placeholders (in a real scenario, we'd use actual .docx files)
        old_file = temp_path / "old_test.docx"
        new_file = temp_path / "new_test.docx"

        # Create simple placeholder files
        old_file.write_text("This is the old content.\nSome additional text here.")
        new_file.write_text(
            "This is the new content.\nSome additional text here.\nAnd a new line."
        )

        print(f"Created test files: {old_file}, {new_file}")

        # Create the diff command
        try:
            DiffDocCommand(old_file, new_file)
            print("Basic functionality test completed (command created).")
        except Exception as e:
            print(f"Error during diff: {e}")


def test_config_functionality():
    """Test configuration functionality."""
    print("\nTesting configuration functionality...")

    # Create a temporary config file
    with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
        import json

        # Create a default config content
        config_data = {
            "DOC_DIFF_TITLE": "Test Comparison",
            "OUTPUT_DIR": str(Path.home()),  # Updated default value
            "COMPARE_MODE": "original",
            "SHOW_CHANGES": True,
            "TRACK_REVISIONS": True,
        }
        json.dump(config_data, f)
        temp_config_path = Path(f.name)

    try:
        # Patch the config file location temporarily
        import sfi.docdiff.docdiff as docdiff_module

        original_config_file = docdiff_module.CONFIG_FILE
        docdiff_module.CONFIG_FILE = temp_config_path

        # Create config instance - should load from our temp file
        config = DocDiffConfig()

        assert config.DOC_DIFF_TITLE == "Test Comparison"
        assert config.SHOW_CHANGES is True
        print("Configuration loading test passed.")

        # Modify config and save
        config.DOC_DIFF_TITLE = "Modified Test"
        config.save()

        # Verify the file was updated
        with open(temp_config_path) as f:
            loaded_data = json.load(f)
            assert loaded_data["DOC_DIFF_TITLE"] == "Modified Test"
        print("Configuration saving test passed.")

    finally:
        # Restore original config file
        docdiff_module.CONFIG_FILE = original_config_file
        # Clean up temp file
        os.unlink(temp_config_path)


def test_command_line_interface():
    """Test command line interface functionality."""
    print("\nTesting command line interface...")

    import subprocess
    import sys

    # Test help command
    try:
        result = subprocess.run(
            [
                sys.executable,
                "-c",
                "from sfi.docdiff.docdiff import main; import sys; sys.argv = ['docdiff', '--help']; main()",
            ],
            capture_output=True,
            text=True,
            timeout=10,
        )

        if result.returncode == 0 or "usage:" in result.stdout:
            print("Command line help test passed.")
        else:
            print(f"Command line help test failed: {result.stderr}")
    except subprocess.TimeoutExpired:
        print("Command line test timed out.")
    except Exception as e:
        print(f"Command line test error: {e}")


def test_error_handling():
    """Test error handling in various scenarios."""
    print("\nTesting error handling...")

    # Test with non-existent files using the command pattern
    from pathlib import Path

    old_file = Path("nonexistent_old.docx")
    new_file = Path("nonexistent_new.docx")

    # Test command creation with non-existent files
    try:
        DiffDocCommand(old_file, new_file)
        # When we try to run the command, it should handle the error appropriately
        print("Command created with non-existent files (will fail on run).")
    except Exception as e:
        print(f"Error during command creation: {e}")


def main():
    """Run all functional tests."""
    print("Running functional tests for docdiff module...\n")

    test_config_functionality()
    test_error_handling()

    # Only run the basic functionality test if on Windows
    import platform

    if platform.system() == "Windows":
        test_basic_functionality()
    else:
        print(
            "Skipping functional test: docdiff only works on Windows with Word installed"
        )

    test_command_line_interface()

    print("\nFunctional tests completed.")


if __name__ == "__main__":
    main()
