"""Fixture utilities for e2e and dialogue understanding tests."""

from typing import TYPE_CHECKING, List, Optional, Union

from rasa.e2e_test.e2e_test_case import TestCaseFixtures

if TYPE_CHECKING:
    from rasa.e2e_test.e2e_test_case import (
        DialogueUnderstandingTestCase,
        Fixture,
        TestCase,
    )


def collect_fixtures_for_test_case(
    test_case: Union["TestCase", "DialogueUnderstandingTestCase"],
    fixtures: List["Fixture"],
) -> List["Fixture"]:
    """Return only the fixtures used by this test case.

    If the test case has no fixture_names, returns an empty list.
    Otherwise returns fixtures for those names, skipping any
    that are not in fixtures (validation will report missing ones).

    Args:
        test_case: The test case.
        fixtures: List of fixtures for the file.

    Returns:
        List of Fixture objects used by the test case.
    """
    if not test_case.fixture_names:
        return []
    return [fixture for fixture in fixtures if fixture.name in test_case.fixture_names]


def extract_test_case_fixtures(
    test_cases: List[Union["TestCase", "DialogueUnderstandingTestCase"]],
    fixtures: Optional[List["Fixture"]],
) -> List["TestCaseFixtures"]:
    """Build TestCaseFixtures for each test case from resolved fixtures.

    Args:
        test_cases: Test cases from the file.
        fixtures: List of fixtures for the file, or None.

    Returns:
        List of TestCaseFixtures (one per test case, only fixtures used by each).
    """
    if not fixtures:
        return []

    fixtures_per_test: List[TestCaseFixtures] = []
    for test_case in test_cases:
        if used_fixtures := collect_fixtures_for_test_case(test_case, fixtures):
            fixtures_per_test.append(
                TestCaseFixtures(
                    test_case_name=test_case.name,
                    file=test_case.file,
                    fixtures=used_fixtures,
                )
            )
    return fixtures_per_test


def get_fixtures_for_test_case(
    test_case: Union["TestCase", "DialogueUnderstandingTestCase"],
    fixtures_per_test: List[TestCaseFixtures],
) -> List["Fixture"]:
    """Finds the fixtures for a test case in the fixtures_per_test.

    Args:
        test_case: The test case to find the fixtures for.
        fixtures_per_test: The fixtures per test case.

    Returns:
        The fixtures for the test case.
    """
    for test_case_fixture in fixtures_per_test:
        if (
            test_case_fixture.test_case_name == test_case.name
            and test_case_fixture.file == test_case.file
        ):
            return test_case_fixture.fixtures
    return []
