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

Each subcommand is a self-contained check that prints a sentinel on success.
"""

from __future__ import annotations

import sys
from datetime import datetime
from pathlib import Path
from unittest.mock import MagicMock, patch

# Ensure the local source tree takes priority over any installed copy.
_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.plan import app as plan_app  # noqa: E402
from cleveragents.domain.models.core.action import Action, ActionState  # noqa: E402
from cleveragents.domain.models.core.plan import (  # noqa: E402
    NamespacedName,
    Plan,
    PlanIdentity,
    PlanPhase,
    PlanTimestamps,
    ProcessingState,
    ProjectLink,
)

runner = CliRunner()

_PLAN_ULID = "01KHDE6WWS2171PWW3GJEBXZ8S"


def _mock_action(name: str = "local/smoke-action") -> Action:
    return Action(
        namespaced_name=NamespacedName.parse(name),
        description="Smoke test action",
        long_description=None,
        definition_of_done="All smoke tests pass",
        strategy_actor="openai/gpt-4",
        execution_actor="openai/gpt-4",
        reusable=True,
        read_only=False,
        state=ActionState.AVAILABLE,
        created_by=None,
        created_at=datetime.now(),
        updated_at=datetime.now(),
    )


def _mock_plan(
    project_links: list[ProjectLink] | None = None,
) -> Plan:
    now = datetime.now()
    return Plan(
        identity=PlanIdentity(plan_id=_PLAN_ULID),
        namespaced_name=NamespacedName.parse("local/smoke-plan"),
        description="Smoke test plan",
        definition_of_done="All smoke tests pass",
        action_name="local/smoke-action",
        phase=PlanPhase.STRATEGIZE,
        processing_state=ProcessingState.QUEUED,
        project_links=project_links or [ProjectLink(project_name="proj-a")],
        arguments={},
        arguments_order=[],
        strategy_actor="openai/gpt-4",
        execution_actor="openai/gpt-4",
        reusable=True,
        read_only=False,
        created_by=None,
        timestamps=PlanTimestamps(created_at=now, updated_at=now),
    )


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


def use_env_priority_override() -> None:
    """Verify plan use accepts --execution-env-priority override."""
    mock_service = MagicMock()
    mock_service.get_action_by_name.return_value = _mock_action()
    mock_service.use_action.return_value = _mock_plan()
    with patch(
        "cleveragents.cli.commands.plan._get_lifecycle_service",
        return_value=mock_service,
    ):
        result = runner.invoke(
            plan_app,
            [
                "use",
                "local/smoke-action",
                "proj-a",
                "--execution-environment",
                "container",
                "--execution-env-priority",
                "override",
            ],
        )
        if result.exit_code == 0:
            plan = mock_service.use_action.return_value
            if plan.execution_env_priority == "override":
                print("plan-env-priority-override-ok")
            else:
                print(
                    f"FAIL: priority={plan.execution_env_priority!r}",
                    file=sys.stderr,
                )
                sys.exit(1)
        else:
            print(f"FAIL: exit code {result.exit_code}", file=sys.stderr)
            print(result.output, file=sys.stderr)
            sys.exit(1)


def use_env_priority_fallback() -> None:
    """Verify plan use accepts --execution-env-priority fallback."""
    mock_service = MagicMock()
    mock_service.get_action_by_name.return_value = _mock_action()
    mock_service.use_action.return_value = _mock_plan()
    with patch(
        "cleveragents.cli.commands.plan._get_lifecycle_service",
        return_value=mock_service,
    ):
        result = runner.invoke(
            plan_app,
            [
                "use",
                "local/smoke-action",
                "proj-a",
                "--execution-environment",
                "host",
                "--execution-env-priority",
                "fallback",
            ],
        )
        if result.exit_code == 0:
            plan = mock_service.use_action.return_value
            if plan.execution_env_priority == "fallback":
                print("plan-env-priority-fallback-ok")
            else:
                print(
                    f"FAIL: priority={plan.execution_env_priority!r}",
                    file=sys.stderr,
                )
                sys.exit(1)
        else:
            print(f"FAIL: exit code {result.exit_code}", file=sys.stderr)
            print(result.output, file=sys.stderr)
            sys.exit(1)


def use_priority_no_env() -> None:
    """Verify --execution-env-priority without --execution-environment fails."""
    mock_service = MagicMock()
    mock_service.get_action_by_name.return_value = _mock_action()
    mock_service.use_action.return_value = _mock_plan()
    with patch(
        "cleveragents.cli.commands.plan._get_lifecycle_service",
        return_value=mock_service,
    ):
        result = runner.invoke(
            plan_app,
            [
                "use",
                "local/smoke-action",
                "proj-a",
                "--execution-env-priority",
                "override",
            ],
        )
        if (
            result.exit_code != 0
            and "--execution-env-priority requires" in result.output
        ):
            print("plan-env-priority-no-env-ok")
        else:
            print(
                f"FAIL: expected failure, got exit code {result.exit_code}",
                file=sys.stderr,
            )
            print(result.output, file=sys.stderr)
            sys.exit(1)


def use_env_default_priority() -> None:
    """Verify env without priority defaults to fallback."""
    mock_service = MagicMock()
    mock_service.get_action_by_name.return_value = _mock_action()
    mock_service.use_action.return_value = _mock_plan()
    with patch(
        "cleveragents.cli.commands.plan._get_lifecycle_service",
        return_value=mock_service,
    ):
        result = runner.invoke(
            plan_app,
            [
                "use",
                "local/smoke-action",
                "proj-a",
                "--execution-environment",
                "container",
            ],
        )
        if result.exit_code == 0:
            plan = mock_service.use_action.return_value
            if plan.execution_env_priority == "fallback":
                print("plan-env-default-priority-ok")
            else:
                print(
                    f"FAIL: expected fallback, got {plan.execution_env_priority!r}",
                    file=sys.stderr,
                )
                sys.exit(1)
        else:
            print(f"FAIL: exit code {result.exit_code}", file=sys.stderr)
            print(result.output, file=sys.stderr)
            sys.exit(1)


def use_invalid_priority() -> None:
    """Verify invalid --execution-env-priority value is rejected."""
    mock_service = MagicMock()
    mock_service.get_action_by_name.return_value = _mock_action()
    mock_service.use_action.return_value = _mock_plan()
    with patch(
        "cleveragents.cli.commands.plan._get_lifecycle_service",
        return_value=mock_service,
    ):
        result = runner.invoke(
            plan_app,
            [
                "use",
                "local/smoke-action",
                "proj-a",
                "--execution-environment",
                "container",
                "--execution-env-priority",
                "invalid-value",
            ],
        )
        if result.exit_code != 0 and "Invalid execution env priority" in result.output:
            print("plan-env-invalid-priority-ok")
        else:
            print(
                f"FAIL: expected failure, got exit code {result.exit_code}",
                file=sys.stderr,
            )
            print(result.output, file=sys.stderr)
            sys.exit(1)


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

_COMMANDS = {
    "use-env-priority-override": use_env_priority_override,
    "use-env-priority-fallback": use_env_priority_fallback,
    "use-priority-no-env": use_priority_no_env,
    "use-env-default-priority": use_env_default_priority,
    "use-invalid-priority": use_invalid_priority,
}


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()
