"""Tests for textual_mcp.app_loader — TDD Red phase."""

from pathlib import Path

import pytest
from textual.app import App

APPS_DIR = Path(__file__).parent / "apps"


class TestLoadAppFromFile:
    """Test loading apps from .py file paths."""

    def test_discovers_first_app_subclass(self):
        """Test 1.1: load_app discovers and instantiates first App subclass."""
        from textual_mcp.app_loader import load_app

        app = load_app(str(APPS_DIR / "simple_app.py"))
        assert app is not None
        assert isinstance(app, App)

    def test_loads_named_class(self):
        """Test 1.2: load_app with :ClassName loads the named class."""
        from textual_mcp.app_loader import load_app

        app = load_app(f"{APPS_DIR / 'simple_app.py'}:SimpleApp")
        assert app is not None
        assert type(app).__name__ == "SimpleApp"

    def test_nonexistent_file_raises_file_not_found(self):
        """Test 1.4: load_app with nonexistent file raises FileNotFoundError."""
        from textual_mcp.app_loader import load_app

        with pytest.raises(FileNotFoundError):
            load_app("/tmp/does_not_exist_abc123.py")

    def test_no_app_subclass_raises_value_error(self):
        """Test 1.5: load_app on file without App subclass raises ValueError."""
        from textual_mcp.app_loader import load_app

        with pytest.raises(ValueError, match="No App subclass found"):
            load_app(str(APPS_DIR / "no_app.py"))

    def test_named_class_not_found_raises_attribute_error(self):
        """Test 1.6: load_app with :NonExistent raises AttributeError."""
        from textual_mcp.app_loader import load_app

        with pytest.raises(AttributeError):
            load_app(f"{APPS_DIR / 'simple_app.py'}:NonExistentApp")


class TestLoadAppFromModule:
    """Test loading apps from module paths."""

    def test_loads_from_module_path(self):
        """Test 1.3: load_app with module:Class imports from installed module."""
        from textual_mcp.app_loader import load_app

        # textual.app:App is always available
        app = load_app("textual.demo.demo_app:DemoApp")
        assert isinstance(app, App)


class TestLoadAppReturnType:
    """Test return type guarantees."""

    def test_loaded_app_is_app_instance(self):
        """Test 1.7: loaded app is instance of textual.app.App."""
        from textual_mcp.app_loader import load_app

        app = load_app(str(APPS_DIR / "simple_app.py"))
        assert isinstance(app, App)
        # Verify it's specifically a SimpleApp
        assert type(app).__name__ == "SimpleApp"
