# Copyright (C) 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Test module for launcher."""

from dataclasses import dataclass
import pathlib

import pytest

from ansys.tools.common.launcher import config, launch_product

from .simple_test_launcher import SimpleLauncher, SimpleLauncherConfig

PRODUCT_NAME = "TestProduct"
LAUNCH_MODE = "direct"


@dataclass
class OtherConfig:
    """Mock configuration class for testing."""

    int_attr: int


@pytest.fixture(autouse=True)
def monkeypatch_entrypoints(monkeypatch_entrypoints_from_plugins):
    """Mock the entry points for the launcher plugins."""
    monkeypatch_entrypoints_from_plugins({PRODUCT_NAME: {"direct": SimpleLauncher}})


def check_uds_file_removed(server):
    """Check that the UDS file has been removed after stopping the server."""
    uds_file = pathlib.Path(server._launcher.transport_options["main"].uds_dir) / "simple_test_service.sock"
    assert not pathlib.Path(uds_file).exists()


def test_default_config():
    """Test the default configuration."""
    config.set_config_for(product_name=PRODUCT_NAME, launch_mode=LAUNCH_MODE, config=SimpleLauncherConfig())
    server = launch_product(PRODUCT_NAME)
    server.wait(timeout=10)
    server.stop()
    assert not server.check()
    check_uds_file_removed(server)


def test_explicit_config():
    """Test that the server can be launched with an explicit configuration."""
    server = launch_product(PRODUCT_NAME, launch_mode=LAUNCH_MODE, config=SimpleLauncherConfig())
    server.wait(timeout=10)
    server.stop()
    assert not server.check()
    check_uds_file_removed(server)


def test_stop_with_timeout():
    """Test that the server can be stopped with a timeout and that it stops correctly."""
    server = launch_product(PRODUCT_NAME, launch_mode=LAUNCH_MODE, config=SimpleLauncherConfig())
    server.wait(timeout=10)
    server.stop(timeout=1.0)
    assert not server.check()
    check_uds_file_removed(server)


def test_invalid_launch_mode_raises():
    """Test that passing an invalid launch mode raises a KeyError."""
    with pytest.raises(KeyError):
        launch_product(PRODUCT_NAME, launch_mode="invalid_launch_mode", config=SimpleLauncherConfig())


def test_invalid_config_raises():
    """Test that passing an invalid configuration type raises a TypeError."""
    with pytest.raises(TypeError):
        launch_product(PRODUCT_NAME, launch_mode=LAUNCH_MODE, config=OtherConfig(int_attr=3))


def test_contextmanager():
    """Test that the context manager works correctly, starting and stopping the server."""
    with launch_product(PRODUCT_NAME, launch_mode=LAUNCH_MODE, config=SimpleLauncherConfig()) as server:
        server.wait(timeout=10)
        assert server.check()
    assert not server.check()
    check_uds_file_removed(server)
