"""Robot Framework helper for skill protocol type validation.

Provides a CLI-style interface for Robot to invoke protocol type
creation and validation.  Exit code 0 = success, 1 = failure.

Usage:
    python robot/helper_skill_protocol.py create-metadata
    python robot/helper_skill_protocol.py create-error
    python robot/helper_skill_protocol.py create-result
    python robot/helper_skill_protocol.py create-definition
    python robot/helper_skill_protocol.py map-error
    python robot/helper_skill_protocol.py error-types
"""

from __future__ import annotations

import sys
from pathlib import Path

# Ensure the src directory is on the 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.skill import (  # noqa: E402
    Skill,
    SkillResolver,
)
from cleveragents.skills.protocol import (  # noqa: E402
    SkillDefinition,
    SkillError,
    SkillErrorType,
    SkillMetadata,
    SkillResult,
    map_tool_error,
)


def _cmd_create_metadata() -> int:
    """Test SkillMetadata.from_skill."""
    skill = Skill(name="local/robot-skill", description="Robot test skill")
    meta = SkillMetadata.from_skill(skill)
    if meta.name != "local/robot-skill":
        print(f"skill-protocol-fail: unexpected name {meta.name}")
        return 1
    print(f"skill-protocol-metadata-ok: {meta.name}")
    return 0


def _cmd_create_error() -> int:
    """Test SkillError creation."""
    err = SkillError(
        error_type=SkillErrorType.TOOL_EXECUTION_FAILURE,
        message="Test error",
        skill_name="local/robot-skill",
    )
    if err.error_type != SkillErrorType.TOOL_EXECUTION_FAILURE:
        print(f"skill-protocol-fail: unexpected type {err.error_type}")
        return 1
    print(f"skill-protocol-error-ok: {err.error_type.value}")
    return 0


def _cmd_create_result() -> int:
    """Test SkillResult creation."""
    result = SkillResult(
        skill_name="local/robot-skill",
        tool_name="local/robot-tool",
        success=True,
        output_data={"status": "ok"},
    )
    if not result.success:
        print("skill-protocol-fail: result not success")
        return 1
    print("skill-protocol-result-ok")
    return 0


def _cmd_create_definition() -> int:
    """Test SkillDefinition creation."""
    skill = Skill(
        name="local/robot-def",
        description="Robot definition test",
        tool_refs=["local/tool-a"],
    )
    resolver = SkillResolver()
    resolved = resolver.resolve_tools(skill, {})
    meta = SkillMetadata.from_skill(skill, resolved=resolved)
    defn = SkillDefinition(
        skill=skill,
        resolved_tools=resolved,
        metadata=meta,
    )
    if defn.skill.name != "local/robot-def":
        print(f"skill-protocol-fail: unexpected name {defn.skill.name}")
        return 1
    print(f"skill-protocol-definition-ok: {defn.skill.name}")
    return 0


def _cmd_map_error() -> int:
    """Test error mapping."""
    mapped = map_tool_error(
        ValueError("Cycle detected"),
        skill_name="local/robot-skill",
    )
    if mapped.error_type != SkillErrorType.CYCLE_DETECTED:
        print(f"skill-protocol-fail: unexpected type {mapped.error_type}")
        return 1
    print(f"skill-protocol-map-ok: {mapped.error_type.value}")
    return 0


def _cmd_error_types() -> int:
    """Test SkillErrorType enum members."""
    members = list(SkillErrorType)
    if len(members) != 7:
        print(f"skill-protocol-fail: expected 7 error types, got {len(members)}")
        return 1
    print(f"skill-protocol-error-types-ok: {len(members)}")
    return 0


_COMMANDS = {
    "create-metadata": _cmd_create_metadata,
    "create-error": _cmd_create_error,
    "create-result": _cmd_create_result,
    "create-definition": _cmd_create_definition,
    "map-error": _cmd_map_error,
    "error-types": _cmd_error_types,
}


def main() -> int:
    """Entry point called by Robot Framework ``Run Process``."""
    if len(sys.argv) < 2:
        print(
            "Usage: helper_skill_protocol.py "
            "<create-metadata|create-error|create-result|create-definition|map-error|error-types>"
        )
        return 1

    command = sys.argv[1]
    handler = _COMMANDS.get(command)
    if handler is None:
        print(f"Unknown command: {command}")
        return 1

    return handler()


if __name__ == "__main__":
    sys.exit(main())
