"""Step definitions for TDD Issue #6885 — CLI registry bootstrap."""

from __future__ import annotations

import os
import shutil
import tempfile
from pathlib import Path

from behave import given, then, when
from typer.testing import CliRunner

import cleveragents.cli.bootstrap as cli_bootstrap
from cleveragents.application.container import reset_container
from cleveragents.cli.commands.tool import app as tool_app
from cleveragents.cli.commands.validation import app as validation_app
from cleveragents.config.settings import Settings


def _reset_settings() -> None:
    """Reset singleton settings between scenarios."""

    Settings.reset()


@given("a CLI runner without a bootstrapped registry database")
def step_no_bootstrap(context) -> None:
    context.runner = CliRunner()

    reset_container()
    _reset_settings()

    cli_bootstrap.reset_bootstrap_state()

    tmpdir = tempfile.mkdtemp(prefix="tdd_tool_cli_bootstrap_6885_")
    db_path = Path(tmpdir) / "registry.db"

    context._tool_cli_tmpdir = tmpdir
    context._tool_cli_db_path = db_path

    os.environ["CLEVERAGENTS_DATABASE_URL"] = f"sqlite:///{db_path}"

    def _cleanup() -> None:
        os.environ.pop("CLEVERAGENTS_DATABASE_URL", None)
        cli_bootstrap.reset_bootstrap_state()
        reset_container()
        _reset_settings()
        shutil.rmtree(tmpdir, ignore_errors=True)

    context.add_cleanup(_cleanup)


@when("I invoke tool list without prior bootstrap")
def step_invoke_tool_list(context) -> None:
    context.result = context.runner.invoke(tool_app, ["list"])


@when("I invoke validation add without prior bootstrap")
def step_invoke_validation_add(context) -> None:
    config_path = Path(context._tool_cli_tmpdir) / "validation.yaml"
    config_path.write_text(
        """
name: local/test-validation
description: temporary validation for TDD issue 6885
source: custom
mode: informational
code: |
  def run(inputs):
      return {"passed": True}
""".strip()
    )

    context.result = context.runner.invoke(
        validation_app,
        [
            "add",
            "--config",
            str(config_path),
            "--format",
            "json",
        ],
    )


@then("the tool list command should exit successfully")
def step_tool_list_exit_ok(context) -> None:
    assert context.result.exit_code == 0, (
        f"Expected exit code 0, got {context.result.exit_code}.\n"
        f"Output:\n{context.result.output}\n"
        f"Exception: {getattr(context.result, 'exception', None)!r}"
    )


@then("the validation add command should exit successfully")
def step_validation_add_exit_ok(context) -> None:
    assert context.result.exit_code == 0, (
        f"Expected exit code 0, got {context.result.exit_code}.\n"
        f"Output:\n{context.result.output}\n"
        f"Exception: {getattr(context.result, 'exception', None)!r}"
    )


@then("the tool list output should indicate that no tools are registered")
def step_tool_list_output(context) -> None:
    output = context.result.output
    assert "No tools found" in output, (
        f"Expected 'No tools found' in output.\nActual output:\n{output}"
    )


@then("the validation add output should report the registered validation in JSON")
def step_validation_add_output(context) -> None:
    output = context.result.output
    assert '"name": "local/test-validation"' in output, (
        "Expected the registered validation name in the JSON output."
    )
