"""Robot Framework helper for WF17 project execution env priority E2E tests."""

from __future__ import annotations

import json
import sys
from pathlib import Path

_SRC = str(Path(__file__).resolve().parents[1] / "src")
if _SRC not in sys.path:
    sys.path.insert(0, _SRC)

from cleveragents.domain.models.core.plan import ExecutionEnvPriority  # noqa: E402


def _run_set_priority() -> None:
    """Test that project-level priority can be set and persisted."""
    # Simulate what project_context.py does: validate the enum
    try:
        p = ExecutionEnvPriority("override")
        assert p == ExecutionEnvPriority.OVERRIDE
    except ValueError:
        print("FAIL: override not a valid ExecutionEnvPriority", file=sys.stderr)
        sys.exit(1)

    try:
        p2 = ExecutionEnvPriority("fallback")
        assert p2 == ExecutionEnvPriority.FALLBACK
    except ValueError:
        print("FAIL: fallback not a valid ExecutionEnvPriority", file=sys.stderr)
        sys.exit(1)

    # Verify invalid values are rejected
    try:
        ExecutionEnvPriority("invalid")
        print("FAIL: 'invalid' should not be a valid priority", file=sys.stderr)
        sys.exit(1)
    except ValueError:
        pass

    print("set-priority-ok")


def _run_show_priority() -> None:
    """Test that persisted priority data round-trips correctly."""
    blob = {
        "execution_environment": "container",
        "execution_env_priority": "override",
    }
    serialized = json.dumps(blob)
    deserialized = json.loads(serialized)

    assert deserialized["execution_env_priority"] == "override"
    assert deserialized["execution_environment"] == "container"

    # Verify the priority value can be loaded into the enum
    p = ExecutionEnvPriority(deserialized["execution_env_priority"])
    assert p == ExecutionEnvPriority.OVERRIDE

    print("show-priority-ok")


_COMMANDS = {
    "set-priority": _run_set_priority,
    "show-priority": _run_show_priority,
}

if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "all"
    if cmd == "all":
        for fn in _COMMANDS.values():
            fn()
    elif cmd in _COMMANDS:
        _COMMANDS[cmd]()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
