"""Step definitions for TDD issue #2922: A2A Python SDK dependency."""

from __future__ import annotations

import importlib
import tomllib
from pathlib import Path
from typing import Any

from behave import given, then, when
from behave.runner import Context


@given('the pyproject.toml file exists at "{path}"')
def step_pyproject_exists(context: Context, path: str) -> None:
    """Verify pyproject.toml exists at the given path."""
    pyproject_path = Path(path)
    assert pyproject_path.exists(), f"pyproject.toml not found at {path}"
    context.pyproject_path = pyproject_path


@when("I read the project dependencies from pyproject.toml")
def step_read_project_dependencies(context: Context) -> None:
    """Read the [project.dependencies] list from pyproject.toml."""
    content = context.pyproject_path.read_bytes()
    data: dict[str, Any] = tomllib.loads(content.decode("utf-8"))
    context.project_dependencies = data.get("project", {}).get("dependencies", [])


@then(
    'the dependency list should include a package that provides the "{module}" module'
)
def step_dependency_provides_module(context: Context, module: str) -> None:
    """Assert that a dependency providing the given module is listed."""
    deps: list[str] = context.project_dependencies
    # The a2a-sdk package installs as the 'a2a' module.
    # Accept either 'a2a-sdk' or 'a2a' as the package name.
    found = any(
        dep.lower().startswith("a2a-sdk") or dep.lower().startswith("a2a>=")
        for dep in deps
    )
    assert found, (
        f"No dependency providing the '{module}' module found in "
        f"[project.dependencies]. Current deps: {deps}"
    )


@when('I attempt to import the "{module_name}" module')
def step_attempt_import(context: Context, module_name: str) -> None:
    """Attempt to import the given module and record the result."""
    try:
        context.imported_module = importlib.import_module(module_name)
        context.import_error = None
    except ImportError as exc:
        context.imported_module = None
        context.import_error = exc


@then("the import should succeed without errors")
def step_import_succeeded(context: Context) -> None:
    """Assert that the previous import attempt succeeded."""
    assert context.import_error is None, f"Import failed with: {context.import_error}"
    assert context.imported_module is not None, "Module was not imported"


@when('I import "{module_path}" and access "{attr_name}"')
def step_import_and_access(context: Context, module_path: str, attr_name: str) -> None:
    """Import a module and access a named attribute."""
    try:
        mod = importlib.import_module(module_path)
        context.accessed_attr = getattr(mod, attr_name, None)
        context.access_error = None
    except ImportError as exc:
        context.accessed_attr = None
        context.access_error = exc


@then('the "{attr_name}" class should be available')
def step_class_available(context: Context, attr_name: str) -> None:
    """Assert that the accessed attribute is a class."""
    assert context.access_error is None, f"Import failed with: {context.access_error}"
    assert context.accessed_attr is not None, (
        f"Attribute '{attr_name}' not found in module"
    )
    assert isinstance(context.accessed_attr, type), (
        f"'{attr_name}' is not a class, got {type(context.accessed_attr)}"
    )
