"""Robot Framework helper for CRP domain model validation.

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

Usage:
    python robot/helper_crp_models.py <command>
"""

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.acms.crp import (  # noqa: E402
    AssembledContext,
    ContextBudget,
    ContextFragment,
    ContextRequest,
    DetailLevelMap,
    FragmentProvenance,
)
from cleveragents.skills.builtins.context_ops import (  # noqa: E402
    register_skill_context_tools,
)
from cleveragents.tool.registry import ToolRegistry  # noqa: E402


def main() -> int:
    """Entry point called by Robot Framework ``Run Process``."""
    if len(sys.argv) < 2:
        print("Usage: helper_crp_models.py <command>")
        return 1

    command: str = sys.argv[1]

    if command == "create-request":
        try:
            req = ContextRequest(purpose="Test context request")
            assert req.breadth == 2
            assert req.depth == 3
            print("crp-request-ok")
            return 0
        except Exception as exc:
            print(f"crp-request-fail: {exc}")
            return 1

    if command == "create-fragment":
        try:
            frag = ContextFragment(
                uko_node="uko-py:class/TestClass",
                content="class TestClass: pass",
                detail_depth=4,
                token_count=50,
                relevance_score=0.85,
                provenance=FragmentProvenance(resource_uri="uko-py:module/test"),
            )
            assert frag.token_count == 50
            assert frag.relevance_score == 0.85
            print("crp-fragment-ok")
            return 0
        except Exception as exc:
            print(f"crp-fragment-fail: {exc}")
            return 1

    if command == "create-budget":
        try:
            budget = ContextBudget(max_tokens=8000, reserved_tokens=1000)
            assert budget.available_tokens == 7000
            print("crp-budget-ok")
            return 0
        except Exception as exc:
            print(f"crp-budget-fail: {exc}")
            return 1

    if command == "create-map":
        try:
            dlm = DetailLevelMap(
                domain="uko-code:",
                max_depth=9,
                levels={"MODULE_LISTING": 0, "FULL_SOURCE": 9},
            )
            assert dlm.resolve("MODULE_LISTING") == 0
            assert dlm.resolve("FULL_SOURCE") == 9
            assert dlm.resolve(15) == 9  # clamped
            print("crp-map-ok")
            return 0
        except Exception as exc:
            print(f"crp-map-fail: {exc}")
            return 1

    if command == "reject-budget":
        try:
            ContextBudget(max_tokens=100, reserved_tokens=200)
            print("crp-reject-budget-fail: should have raised")
            return 1
        except Exception:
            print("crp-reject-budget-ok")
            return 0

    if command == "reject-fragment":
        try:
            ContextFragment(
                uko_node="uko-py:test",
                content="test",
                detail_depth=0,
                token_count=10,
                relevance_score=1.5,
                provenance=FragmentProvenance(resource_uri="uko-py:module/test"),
            )
            print("crp-reject-fragment-fail: should have raised")
            return 1
        except Exception:
            print("crp-reject-fragment-ok")
            return 0

    if command == "register-tools":
        try:
            registry = ToolRegistry()
            register_skill_context_tools(registry)
            assert registry.get("builtin/request-context") is not None
            assert registry.get("builtin/query-history") is not None
            assert registry.get("builtin/get-context-budget") is not None
            print("crp-tools-ok")
            return 0
        except Exception as exc:
            print(f"crp-tools-fail: {exc}")
            return 1

    if command == "create-assembled":
        try:
            assembled = AssembledContext(
                total_tokens=1500,
                budget_used=0.75,
                context_hash="abc123def",
                strategies_used=["simple-keyword"],
            )
            assert assembled.total_tokens == 1500
            assert assembled.budget_used == 0.75
            print("crp-assembled-ok")
            return 0
        except Exception as exc:
            print(f"crp-assembled-fail: {exc}")
            return 1

    print(f"Unknown command: {command}")
    return 1


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