"""Helper script for container infrastructure resource type Robot tests.

Usage:
    python helper_resource_type_container_infra.py check-registration
    python helper_resource_type_container_infra.py check-instance-children
    python helper_resource_type_container_infra.py check-hierarchy
    python helper_resource_type_container_infra.py check-yaml-loading
"""

from __future__ import annotations

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.application.services._resource_registry_data import (  # noqa: E402
    BUILTIN_TYPES,
)
from cleveragents.domain.models.core.resource_type import (  # noqa: E402
    ResourceTypeSpec,
)
from cleveragents.resource.schema import (  # noqa: E402
    ResourceTypeConfigSchema,
)

_EXAMPLES = Path(__file__).resolve().parents[1] / "examples" / "resource-types"

_CONTAINER_INFRA_NAMES = [
    "container-runtime",
    "container-image",
    "container-mount",
    "container-exec-env",
    "container-port",
    "container-volume",
    "container-network",
]


def cmd_check_registration() -> None:
    """Verify all 7 container infra types in BUILTIN_TYPES."""
    names = [d["name"] for d in BUILTIN_TYPES]
    for cn in _CONTAINER_INFRA_NAMES:
        assert cn in names, f"{cn} not in BUILTIN_TYPES: {names}"
        assert cn in ResourceTypeSpec.BUILTIN_NAMES, f"{cn} not in BUILTIN_NAMES"
        entry = next(d for d in BUILTIN_TYPES if d["name"] == cn)
        assert entry["resource_kind"] == "physical"
        assert entry["built_in"] is True
    print("check-registration-ok")


def cmd_check_instance_children() -> None:
    """Verify container-instance has updated children."""
    entry = next(d for d in BUILTIN_TYPES if d["name"] == "container-instance")
    for child in ("container-mount", "container-exec-env", "container-port"):
        assert child in entry["child_types"], (
            f"{child} not in container-instance children: {entry['child_types']}"
        )
    for parent in ("container-runtime", "container-image"):
        assert parent in entry["parent_types"], (
            f"{parent} not in container-instance parents: {entry['parent_types']}"
        )
    print("check-instance-children-ok")


def cmd_check_hierarchy() -> None:
    """Verify runtime -> image -> instance DAG."""
    by_name = {d["name"]: d for d in BUILTIN_TYPES}

    runtime = by_name["container-runtime"]
    assert "container-image" in runtime["child_types"]
    assert "container-instance" in runtime["child_types"]
    assert "container-volume" in runtime["child_types"]
    assert "container-network" in runtime["child_types"]

    image = by_name["container-image"]
    assert "container-runtime" in image["parent_types"]
    assert "container-instance" in image["child_types"]

    mount = by_name["container-mount"]
    assert "container-instance" in mount["parent_types"]
    assert "fs-directory" in mount["child_types"]

    volume = by_name["container-volume"]
    assert "container-runtime" in volume["parent_types"]
    assert "fs-directory" in volume["child_types"]

    network = by_name["container-network"]
    assert "container-runtime" in network["parent_types"]
    assert network["child_types"] == []

    print("check-hierarchy-ok")


def cmd_check_yaml_loading() -> None:
    """Load all 7 YAML configs and verify schema."""
    for cn in _CONTAINER_INFRA_NAMES:
        path = _EXAMPLES / f"{cn}.yaml"
        assert path.exists(), f"Missing YAML: {path}"
        schema = ResourceTypeConfigSchema.from_yaml_file(path)
        assert schema.name == cn
        assert schema.resource_kind == "physical"
        spec = ResourceTypeSpec.from_config(schema.model_dump())
        assert spec.name == cn
    print("check-yaml-loading-ok")


_COMMANDS = {
    "check-registration": cmd_check_registration,
    "check-instance-children": cmd_check_instance_children,
    "check-hierarchy": cmd_check_hierarchy,
    "check-yaml-loading": cmd_check_yaml_loading,
}


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(1)
    _COMMANDS[sys.argv[1]]()


if __name__ == "__main__":
    main()
