"""Step definitions for plan lifecycle persistence via repositories."""

from __future__ import annotations

from typing import Any

from behave import given, then, when
from behave.runner import Context
from sqlalchemy import create_engine, event
from sqlalchemy.orm import Session, sessionmaker

from cleveragents.application.services.plan_lifecycle_service import (
    PlanLifecycleService,
)
from cleveragents.config.settings import Settings
from cleveragents.core.exceptions import NotFoundError
from cleveragents.domain.models.core.plan import PlanPhase
from cleveragents.infrastructure.database.models import Base
from cleveragents.infrastructure.database.repositories import (
    ActionRepository,
    DuplicateActionError,
    LifecyclePlanRepository,
)
from cleveragents.infrastructure.database.unit_of_work import UnitOfWork


def _build_test_uow_and_factory() -> tuple[UnitOfWork, sessionmaker[Session], Any]:
    """Build an in-memory UoW suitable for testing.

    Returns (uow, session_factory, engine) where the UoW's
    transaction() context manager yields UnitOfWorkContexts backed
    by a shared in-memory SQLite database.
    """
    engine = create_engine(
        "sqlite:///:memory:",
        echo=False,
        future=True,
        connect_args={"check_same_thread": False},
    )

    @event.listens_for(engine, "connect")
    def _fk(dbapi_conn: Any, _rec: Any) -> None:
        cursor = dbapi_conn.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()

    Base.metadata.create_all(engine)
    sf: sessionmaker[Session] = sessionmaker(
        bind=engine,
        expire_on_commit=False,
        autoflush=False,
        autocommit=False,
        class_=Session,
    )

    # Build a lightweight UoW that uses our test engine directly
    uow = UnitOfWork.__new__(UnitOfWork)
    uow.database_url = "sqlite:///:memory:"
    uow._engine = engine
    uow._session_factory = sf
    uow._database_initialized = True
    uow._prompt_for_migration = None

    return uow, sf, engine


@given("a persisted plan lifecycle service backed by SQLite")
def step_create_persisted_service(context: Context) -> None:
    """Create a PlanLifecycleService backed by an in-memory SQLite UoW."""
    uow, sf, engine = _build_test_uow_and_factory()
    settings = Settings()
    service = PlanLifecycleService(settings=settings, unit_of_work=uow)
    context.persist_service = service
    context.persist_uow = uow
    context.persist_sf = sf
    context.persist_engine = engine
    context.persist_error = None


@given('a persisted action "{name}" exists')
def step_create_persisted_action_exists(context: Context, name: str) -> None:
    """Create a persisted action for subsequent steps."""
    svc: PlanLifecycleService = context.persist_service
    svc.create_action(
        name=name,
        description=f"Action {name}",
        definition_of_done="All tests pass",
        strategy_actor="openai/gpt-4",
        execution_actor="openai/gpt-4",
    )


@when('I create a persisted action "{name}" with definition "{definition}"')
def step_create_persisted_action(context: Context, name: str, definition: str) -> None:
    """Create an action via the persisted service."""
    svc: PlanLifecycleService = context.persist_service
    context.persist_action = svc.create_action(
        name=name,
        description=f"Action {name}",
        definition_of_done=definition,
        strategy_actor="openai/gpt-4",
        execution_actor="openai/gpt-4",
    )


@then('the action "{name}" should be retrievable from a fresh DB session')
def step_action_retrievable_from_db(context: Context, name: str) -> None:
    """Verify the action exists in the DB via a fresh session."""
    sf: sessionmaker[Session] = context.persist_sf
    session = sf()
    repo = ActionRepository(session_factory=lambda: session)
    action = repo.get_by_name(name)
    session.close()
    assert action is not None, f"Action {name} not found in DB"
    assert str(action.namespaced_name) == name


@when('I use the persisted action "{name}" to create a plan')
def step_use_persisted_action(context: Context, name: str) -> None:
    """Use a persisted action to create a plan."""
    svc: PlanLifecycleService = context.persist_service
    context.persist_plan = svc.use_action(action_name=name)


@then("the plan should be retrievable from a fresh DB session")
def step_plan_retrievable_from_db(context: Context) -> None:
    """Verify the plan exists in the DB via a fresh session."""
    plan_id = context.persist_plan.identity.plan_id
    sf: sessionmaker[Session] = context.persist_sf
    session = sf()
    repo = LifecyclePlanRepository(session_factory=lambda: session)
    plan = repo.get(plan_id)
    session.close()
    assert plan is not None, f"Plan {plan_id} not found in DB"
    assert plan.identity.plan_id == plan_id
    assert plan.phase == PlanPhase.STRATEGIZE


@given("a persisted plan in strategize-complete state")
def step_plan_in_strategize_complete(context: Context) -> None:
    """Create a plan in strategize/complete state."""
    svc: PlanLifecycleService = context.persist_service
    svc.create_action(
        name="local/strat-complete",
        description="Test action",
        definition_of_done="Done",
        strategy_actor="openai/gpt-4",
        execution_actor="openai/gpt-4",
    )
    plan = svc.use_action(action_name="local/strat-complete")
    svc.start_strategize(plan.identity.plan_id)
    svc.complete_strategize(plan.identity.plan_id)
    context.persist_plan = svc.get_plan(plan.identity.plan_id)


@when("I execute the persisted plan")
def step_execute_persisted_plan(context: Context) -> None:
    """Execute the persisted plan (strategize->execute transition)."""
    svc: PlanLifecycleService = context.persist_service
    plan_id = context.persist_plan.identity.plan_id
    context.persist_plan = svc.execute_plan(plan_id)


@then('the persisted plan phase should be "{phase}"')
def step_check_persisted_plan_phase(context: Context, phase: str) -> None:
    """Verify the persisted plan's phase in DB."""
    plan_id = context.persist_plan.identity.plan_id
    sf: sessionmaker[Session] = context.persist_sf
    session = sf()
    repo = LifecyclePlanRepository(session_factory=lambda: session)
    plan = repo.get(plan_id)
    session.close()
    assert plan is not None, f"Plan {plan_id} not found in DB"
    assert plan.phase.value == phase, f"Expected phase {phase}, got {plan.phase.value}"


@then('the persisted plan processing state should be "{state}"')
def step_check_persisted_plan_state(context: Context, state: str) -> None:
    """Verify the persisted plan's processing state in DB."""
    plan_id = context.persist_plan.identity.plan_id
    sf: sessionmaker[Session] = context.persist_sf
    session = sf()
    repo = LifecyclePlanRepository(session_factory=lambda: session)
    plan = repo.get(plan_id)
    session.close()
    assert plan is not None, f"Plan {plan_id} not found in DB"
    assert plan.processing_state.value == state, (
        f"Expected state {state}, got {plan.processing_state.value}"
    )


@given("a persisted plan in execute-complete state")
def step_plan_in_execute_complete(context: Context) -> None:
    """Create a plan in execute/complete state."""
    svc: PlanLifecycleService = context.persist_service
    svc.create_action(
        name="local/exec-complete",
        description="Test action",
        definition_of_done="Done",
        strategy_actor="openai/gpt-4",
        execution_actor="openai/gpt-4",
    )
    plan = svc.use_action(action_name="local/exec-complete")
    pid = plan.identity.plan_id
    svc.start_strategize(pid)
    svc.complete_strategize(pid)
    svc.execute_plan(pid)
    svc.start_execute(pid)
    svc.complete_execute(pid)
    context.persist_plan = svc.get_plan(pid)


@when("I apply the persisted plan")
def step_apply_persisted_plan(context: Context) -> None:
    """Apply the persisted plan (execute->apply transition)."""
    svc: PlanLifecycleService = context.persist_service
    plan_id = context.persist_plan.identity.plan_id
    context.persist_plan = svc.apply_plan(plan_id)


@then("listing plans should return {count:d} plan")
def step_list_plans_count(context: Context, count: int) -> None:
    """Verify the plan count from list_plans."""
    svc: PlanLifecycleService = context.persist_service
    plans = svc.list_plans()
    assert len(plans) == count, f"Expected {count} plans, got {len(plans)}"


@when('I try to create another persisted action "{name}"')
def step_try_create_duplicate_action(context: Context, name: str) -> None:
    """Attempt to create a duplicate action."""
    svc: PlanLifecycleService = context.persist_service
    context.persist_error = None
    try:
        svc.create_action(
            name=name,
            description=f"Duplicate {name}",
            definition_of_done="Done",
            strategy_actor="openai/gpt-4",
            execution_actor="openai/gpt-4",
        )
    except (DuplicateActionError, Exception) as exc:
        context.persist_error = exc


@then("the duplicate action creation should fail with an error")
def step_check_duplicate_error(context: Context) -> None:
    """Verify the duplicate creation raised an error."""
    assert context.persist_error is not None, "Expected error, got none"


@when('I try to use a non-existent persisted action "{name}"')
def step_try_use_missing_action(context: Context, name: str) -> None:
    """Attempt to use a non-existent action."""
    svc: PlanLifecycleService = context.persist_service
    context.persist_error = None
    try:
        svc.use_action(action_name=name)
    except NotFoundError as exc:
        context.persist_error = exc


@then('the missing action error should mention "{name}"')
def step_check_missing_action_error(context: Context, name: str) -> None:
    """Verify the error message references the action name."""
    assert context.persist_error is not None, "Expected error, got none"
    assert name in str(context.persist_error), (
        f"Expected '{name}' in error message, got: {context.persist_error}"
    )
