"""Helper script for tdd_session_list_di.robot smoke tests.

Each subcommand exercises the real DI path (no mocks) to reproduce bug #554.
The helper reports the **real** outcome: it exits 0 and prints the sentinel
when the operation succeeds (bug is fixed), and exits 1 when the bug is
still present.  The ``tdd_expected_fail_listener`` on the Robot side handles
pass/fail inversion while the bug remains open.
"""

from __future__ import annotations

import sys
from collections.abc import Callable
from pathlib import Path

# Ensure local source tree AND robot/ directory are importable.
_ROOT = Path(__file__).resolve().parents[1]
_SRC = str(_ROOT / "src")
_ROBOT = str(_ROOT / "robot")
for _p in (_SRC, _ROBOT):
    if _p not in sys.path:
        sys.path.insert(0, _p)

from helper_tdd_session_di_common import runner, setup_real_di, teardown  # noqa: E402

from cleveragents.cli.commands import session as session_mod  # noqa: E402
from cleveragents.cli.commands.session import app as session_app  # noqa: E402

# ---------------------------------------------------------------------------
# Subcommands
# ---------------------------------------------------------------------------


def list_di_error() -> None:
    """Invoke ``session list`` through the real DI path.

    Exits 0 with sentinel when the command succeeds (bug fixed).
    Exits 1 when the command fails (bug still present).
    """
    db_path = setup_real_di()
    try:
        result = runner.invoke(session_app, ["list"])
        if result.exit_code == 0:
            print("tdd-session-list-di-error-ok")
        else:
            print(
                f"session list failed with exit code {result.exit_code}",
                file=sys.stderr,
            )
            sys.exit(1)
    finally:
        teardown(db_path)


def service_resolution() -> None:
    """Call ``_get_session_service()`` to verify DI resolution.

    Exits 0 with sentinel when the service resolves (bug fixed).
    Exits 1 when resolution raises AttributeError (bug still present).
    """
    db_path = setup_real_di()
    try:
        try:
            session_mod._get_session_service()
        except AttributeError as exc:
            print(
                f"_get_session_service() raised {exc!r}",
                file=sys.stderr,
            )
            sys.exit(1)

        print("tdd-session-list-service-resolution-ok")
    finally:
        teardown(db_path)


def list_json() -> None:
    """Invoke ``session list --format json`` through the real DI path.

    Exits 0 with sentinel when the command succeeds (bug fixed).
    Exits 1 when the command fails (bug still present).
    """
    db_path = setup_real_di()
    try:
        result = runner.invoke(session_app, ["list", "--format", "json"])
        if result.exit_code == 0:
            print("tdd-session-list-json-ok")
        else:
            print(
                f"session list --format json failed with exit code {result.exit_code}",
                file=sys.stderr,
            )
            sys.exit(1)
    finally:
        teardown(db_path)


# ---------------------------------------------------------------------------
# Dispatcher
# ---------------------------------------------------------------------------

_COMMANDS: dict[str, Callable[[], None]] = {
    "list-di-error": list_di_error,
    "service-resolution": service_resolution,
    "list-json": list_json,
}

if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] not in _COMMANDS:
        print(
            f"Usage: {sys.argv[0]} <{'|'.join(_COMMANDS)}>",
            file=sys.stderr,
        )
        sys.exit(1)
    cmd = _COMMANDS[sys.argv[1]]
    cmd()
