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

Tests the ``--skill`` flag on the ``actor-run run`` CLI command.
Each subcommand is a self-contained check that prints a sentinel on success.
"""

from __future__ import annotations

import os
import sys
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch

# Ensure local source tree is importable
_SRC = str(Path(__file__).resolve().parents[1] / "src")
if _SRC not in sys.path:
    sys.path.insert(0, _SRC)

from typer.testing import CliRunner  # noqa: E402

from cleveragents.cli.commands.actor_run import app as actor_run_app  # noqa: E402

runner = CliRunner()

_SIMPLE_YAML = """\
name: smoke-actor
type: custom
tools:
  - operation: identity
"""


def _write_yaml(content: str) -> str:
    fd, path = tempfile.mkstemp(suffix=".yaml")
    with os.fdopen(fd, "w") as fh:
        fh.write(content)
    return path


def unknown_skill_exits_with_error() -> None:
    """Verify that ``--skill`` with an unknown skill name exits with code 2."""
    path = _write_yaml(_SIMPLE_YAML)
    try:
        result = runner.invoke(
            actor_run_app,
            [
                "--config",
                path,
                "test-actor",
                "hello",
                "--skill",
                "local/nonexistent-skill",
            ],
        )
        if result.exit_code == 2 and "not found in registry" in result.output:
            print("skill-actor-run-unknown-skill-ok")
        else:
            print(
                f"FAIL: expected exit code 2 with 'not found in registry', "
                f"got code={result.exit_code}",
                file=sys.stderr,
            )
            print(result.output, file=sys.stderr)
            if result.exception:
                import traceback

                traceback.print_exception(
                    type(result.exception),
                    result.exception,
                    result.exception.__traceback__,
                    file=sys.stderr,
                )
            sys.exit(1)
    finally:
        Path(path).unlink(missing_ok=True)


def skill_flag_accepted() -> None:
    """Verify that ``--skill`` with a valid skill name is accepted by the CLI."""
    from cleveragents.application.services.skill_service import SkillService
    from cleveragents.domain.models.core.skill import Skill

    # Build a real in-memory SkillService with a registered skill
    svc = SkillService()
    skill = Skill(
        name="local/smoke-skill",
        description="Smoke test skill",
        tool_refs=["builtin/read_file"],
    )
    svc._skills["local/smoke-skill"] = skill

    mock_container = MagicMock()
    mock_container.skill_service.return_value = svc

    path = _write_yaml(_SIMPLE_YAML)
    try:
        with patch(
            "cleveragents.reactive.application.get_container",
            return_value=mock_container,
        ):
            result = runner.invoke(
                actor_run_app,
                [
                    "--config",
                    path,
                    "test-actor",
                    "hello",
                    "--skill",
                    "local/smoke-skill",
                ],
            )
        # The command may fail for other reasons (no real LLM, etc.) but
        # the important thing is it did NOT fail with "not found in registry"
        # and the skill was accepted.
        if "not found in registry" in (result.output or ""):
            print("FAIL: skill was rejected as not found", file=sys.stderr)
            print(result.output, file=sys.stderr)
            sys.exit(1)
        print("skill-actor-run-flag-accepted-ok")
    finally:
        Path(path).unlink(missing_ok=True)


# ---------------------------------------------------------------------------
# Main dispatcher
# ---------------------------------------------------------------------------

_COMMANDS = {
    "unknown-skill": unknown_skill_exits_with_error,
    "skill-flag-accepted": skill_flag_accepted,
}


def main() -> None:
    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(2)
    _COMMANDS[sys.argv[1]]()


if __name__ == "__main__":
    main()
