"""Step definitions for TDD Bug #1141 — session create does not persist.

Steps exercise the create-then-list round-trip through the real DI path.
All step names use the ``tdd1141`` prefix to avoid ``AmbiguousStep``
collisions with existing session create/list steps.

The shared ``Given a CLI runner using the real session DI path`` step
(from ``tdd_session_shared_steps.py``) handles setup and cleanup:
temp database, DI reset, structlog suppression, and cleanup registration.
"""

from __future__ import annotations

import json

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

from cleveragents.cli.main import app as main_app


@when("I tdd1141 invoke init with force yes")
def step_tdd1141_invoke_init(context: Context) -> None:
    """Invoke ``init --force --yes`` via the root CLI app."""
    context.tdd1141_init_result = context.runner.invoke(
        main_app, ["init", "--force", "--yes"]
    )


@then("the tdd1141 init should exit successfully")
def step_tdd1141_init_exits_ok(context: Context) -> None:
    """Assert init exits with code 0."""
    result = context.tdd1141_init_result
    assert result.exit_code == 0, (
        f"Expected init exit code 0, got {result.exit_code}.\nOutput:\n{result.output}"
    )


@when("I tdd1141 invoke session create")
def step_tdd1141_invoke_create(context: Context) -> None:
    """Invoke ``session create`` through the root CLI app."""
    context.tdd1141_create_result = context.runner.invoke(
        main_app, ["session", "create"]
    )


@then("the tdd1141 session create should exit successfully")
def step_tdd1141_create_exits_ok(context: Context) -> None:
    """Assert session create exits with code 0."""
    result = context.tdd1141_create_result
    assert result.exit_code == 0, (
        f"Expected session create exit code 0, got {result.exit_code}.\n"
        f"Output:\n{result.output}"
    )


@when("I tdd1141 invoke session list with format json")
def step_tdd1141_invoke_list_json(context: Context) -> None:
    """Invoke ``session list --format json`` through the root CLI app."""
    context.tdd1141_list_result = context.runner.invoke(
        main_app, ["session", "list", "--format", "json"]
    )


@then("the tdd1141 session list should exit successfully")
def step_tdd1141_list_exits_ok(context: Context) -> None:
    """Assert session list exits with code 0."""
    result = context.tdd1141_list_result
    assert result.exit_code == 0, (
        f"Expected session list exit code 0, got {result.exit_code}.\n"
        f"Output:\n{result.output}"
    )


@then("the tdd1141 session list output should report total {count:d}")
def step_tdd1141_list_contains_count(context: Context, count: int) -> None:
    """Assert the JSON output reports the expected total session count."""
    output = context.tdd1141_list_result.output
    try:
        data = json.loads(output)
    except json.JSONDecodeError as exc:
        raise AssertionError(
            f"Session list output is not valid JSON:\n{output}"
        ) from exc

    # Support both top-level "total" (empty list case) and nested "summary.total"
    actual = data["total"] if "total" in data else data.get("summary", {}).get("total")
    assert actual == count, (
        f"Expected 'total': {count} in session list output, got {actual!r}.\n"
        f"Full output:\n{output}"
    )
