"""Step definitions for session_service_coverage.feature.

These steps target specific uncovered lines in
src/cleveragents/application/services/session_service.py:
- Lines 97-98:   create() exception branch when event_bus.emit raises
- Lines 139-146: delete() emitting ENTITY_DELETED when event_bus is present
- Lines 150-151: delete() exception branch when event_bus.emit raises
- Line 217:      export_session() SessionNotFoundError
- Line 248:      import_session() missing checksum
- Lines 310-311: import_session() invalid message data (KeyError/ValueError)
"""

import hashlib
import json
from unittest.mock import MagicMock

from behave import given, then, when

from cleveragents.application.services.session_service import PersistentSessionService
from cleveragents.domain.models.core.session import (
    EXPORT_SCHEMA_VERSION,
    SessionImportError,
    SessionNotFoundError,
)
from cleveragents.infrastructure.events.types import EventType


# ---------------------------------------------------------------------------
# Background
# ---------------------------------------------------------------------------
@given("the session service module is imported")
def step_session_service_module_imported(context):
    """Verify the module is importable."""
    assert PersistentSessionService is not None


# ---------------------------------------------------------------------------
# Shared setup helpers
# ---------------------------------------------------------------------------
@given("a mock session repository and message repository")
def step_mock_repos(context):
    """Create mock repositories."""
    context.mock_session_repo = MagicMock()
    context.mock_message_repo = MagicMock()


@given("a persistent session service without event bus")
def step_service_no_event_bus(context):
    """Create service without event bus."""
    context.service = PersistentSessionService(
        session_repo=context.mock_session_repo,
        message_repo=context.mock_message_repo,
        event_bus=None,
    )


# ---------------------------------------------------------------------------
# Lines 97-98: create() with failing event bus
# ---------------------------------------------------------------------------
@given("an event bus that raises on emit")
def step_failing_event_bus(context):
    """Create an event bus whose emit method raises RuntimeError."""
    context.failing_event_bus = MagicMock()
    context.failing_event_bus.emit.side_effect = RuntimeError("emit exploded")


@given("a persistent session service with the failing event bus")
def step_service_with_failing_event_bus(context):
    """Create a service wired to the failing event bus."""
    context.service = PersistentSessionService(
        session_repo=context.mock_session_repo,
        message_repo=context.mock_message_repo,
        event_bus=context.failing_event_bus,
    )


@when('sesscov I create a session with actor name "{actor_name}"')
def step_create_session(context, actor_name):
    """Call create() and store the result."""
    context.created_session = context.service.create(actor_name=actor_name)


@then("the session should be returned successfully")
def step_verify_session_returned(context):
    """Verify a session object was returned despite the emit failure."""
    assert context.created_session is not None
    assert context.created_session.session_id is not None


@then("the session repository should have recorded one create call")
def step_verify_repo_create_called(context):
    """Verify the repo create method was called exactly once."""
    assert context.mock_session_repo.create.call_count == 1


# ---------------------------------------------------------------------------
# Lines 139-146: delete() with recording event bus (emit succeeds)
# ---------------------------------------------------------------------------
@given("a recording event bus")
def step_recording_event_bus(context):
    """Create an event bus that records emitted events."""
    context.recording_event_bus = MagicMock()
    context.recording_event_bus.emitted_events = []

    def record_emit(event):
        context.recording_event_bus.emitted_events.append(event)

    context.recording_event_bus.emit.side_effect = record_emit


@given("a persistent session service with the recording event bus")
def step_service_with_recording_event_bus(context):
    """Create a service wired to the recording event bus."""
    context.service = PersistentSessionService(
        session_repo=context.mock_session_repo,
        message_repo=context.mock_message_repo,
        event_bus=context.recording_event_bus,
    )


@given("the session repository will return True for delete")
def step_repo_delete_returns_true(context):
    """Configure the mock session repo to indicate successful deletion."""
    context.mock_session_repo.delete.return_value = True


@when('I delete session "{session_id}"')
def step_delete_session(context, session_id):
    """Call delete() and capture any exception."""
    context.delete_error = None
    try:
        context.service.delete(session_id)
    except Exception as exc:
        context.delete_error = exc


@then("the recording event bus should have received an ENTITY_DELETED event")
def step_verify_entity_deleted_event(context):
    """Verify the recording event bus captured an ENTITY_DELETED event."""
    assert context.delete_error is None, (
        f"Expected no error from delete, got {context.delete_error!r}"
    )
    emitted = context.recording_event_bus.emitted_events
    assert len(emitted) == 1, f"Expected 1 emitted event, got {len(emitted)}"
    event = emitted[0]
    assert event.event_type == EventType.ENTITY_DELETED


# ---------------------------------------------------------------------------
# Lines 150-151: delete() with failing event bus
# ---------------------------------------------------------------------------
@then("no exception should be raised from delete")
def step_verify_no_delete_exception(context):
    """Verify delete completed without propagating an exception."""
    assert context.delete_error is None, (
        f"Expected no error, got {context.delete_error!r}"
    )


# ---------------------------------------------------------------------------
# Line 217: export_session() — session not found
# ---------------------------------------------------------------------------
@given("the session repository returns None for get_by_id")
def step_repo_get_returns_none(context):
    """Configure the mock session repo to return None for any get_by_id."""
    context.mock_session_repo.get_by_id.return_value = None


@when('I export session "{session_id}"')
def step_export_session(context, session_id):
    """Call export_session() and capture any exception."""
    context.export_error = None
    try:
        context.export_result = context.service.export_session(session_id)
    except Exception as exc:
        context.export_error = exc


@then('a SessionNotFoundError should be raised with message containing "{text}"')
def step_verify_session_not_found_error(context, text):
    """Verify a SessionNotFoundError was raised with the expected text."""
    assert context.export_error is not None, "Expected an error but none was raised"
    assert isinstance(context.export_error, SessionNotFoundError), (
        f"Expected SessionNotFoundError, got {type(context.export_error).__name__}"
    )
    assert text in str(context.export_error), (
        f"Expected '{text}' in error message, got '{context.export_error}'"
    )


# ---------------------------------------------------------------------------
# Line 248: import_session() — missing checksum
# ---------------------------------------------------------------------------
@when("I import session data with valid schema version but no checksum")
def step_import_missing_checksum(context):
    """Call import_session() with data that has schema_version but no checksum."""
    data = {
        "schema_version": EXPORT_SCHEMA_VERSION,
        "session_id": "01JTESTIMPORT000000000000000",
        "actor_name": None,
        "messages": [],
        # Note: no "checksum" key at all
    }
    context.import_error = None
    try:
        context.import_result = context.service.import_session(data)
    except Exception as exc:
        context.import_error = exc


@then('a SessionImportError should be raised with message containing "{text}"')
def step_verify_session_import_error(context, text):
    """Verify a SessionImportError was raised with the expected text."""
    assert context.import_error is not None, "Expected an error but none was raised"
    assert isinstance(context.import_error, SessionImportError), (
        f"Expected SessionImportError, got {type(context.import_error).__name__}"
    )
    assert text in str(context.import_error), (
        f"Expected '{text}' in error message, got '{context.import_error}'"
    )


# ---------------------------------------------------------------------------
# Lines 310-311: import_session() — invalid message data
# ---------------------------------------------------------------------------
@when("I import session data with valid checksum but invalid message fields")
def step_import_invalid_messages(context):
    """Create import data with a valid checksum but messages that lack required keys.

    The messages list contains an entry missing the required "role" key,
    which will cause a KeyError during parsing and trigger lines 310-311.
    """
    data_without_checksum = {
        "schema_version": EXPORT_SCHEMA_VERSION,
        "session_id": "01JTESTIMPORT000000000000000",
        "actor_name": None,
        "namespace": "local",
        "linked_plan_ids": [],
        "token_usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "estimated_cost": 0.0,
        },
        "metadata": {},
        "created_at": "2025-01-01T00:00:00",
        "updated_at": "2025-01-01T00:00:00",
        "messages": [
            {
                # Missing "role" key — will cause KeyError at line 272
                "content": "hello",
                "sequence": 0,
                "timestamp": "2025-01-01T00:00:00",
            }
        ],
    }

    # Compute a valid checksum so that checksum verification passes
    # Note: import_session expects just the hex digest in data["checksum"],
    # then prepends "sha256:" internally for comparison.
    canonical = json.dumps(data_without_checksum, sort_keys=True, default=str)
    checksum_hex = hashlib.sha256(canonical.encode()).hexdigest()

    data_with_checksum = {**data_without_checksum, "checksum": checksum_hex}

    context.import_error = None
    try:
        context.import_result = context.service.import_session(data_with_checksum)
    except Exception as exc:
        context.import_error = exc
