"""Simple test runner for ActionRegistry without pytest."""

import json
import tempfile
from pathlib import Path
from unishell.core.action_registry import (
    ActionRegistryImpl,
    ActionSchema,
    PermissionLevel,
    RiskLevel,
    RollbackStrategy
)


def test_load_from_json():
    """Test loading action from JSON file."""
    registry = ActionRegistryImpl()
    
    with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
        action_data = {
            "action_id": "test.action",
            "category": "test",
            "required_params": ["param1"],
            "permission_level": "user",
            "risk_level": "low",
            "execution": {"requires_confirmation": False},
            "rollback_strategy": "none"
        }
        json.dump(action_data, f)
        temp_file = f.name
    
    registry.load_from_file(temp_file)
    
    assert "test.action" in registry.list_actions()
    action = registry.get_action("test.action")
    assert action.action_id == "test.action"
    assert action.category == "test"
    print("[PASS] test_load_from_json")


def test_load_from_dict():
    """Test loading action from dictionary."""
    registry = ActionRegistryImpl()
    
    action_data = {
        "action_id": "dict.action",
        "category": "test",
        "required_params": ["param1", "param2"],
        "permission_level": "admin",
        "risk_level": "high",
        "execution": {"timeout": 60},
        "rollback_strategy": "automatic"
    }
    
    registry.load_from_dict(action_data)
    
    action = registry.get_action("dict.action")
    assert action is not None
    assert action.action_id == "dict.action"
    assert len(action.required_params) == 2
    print("[PASS] test_load_from_dict")


def test_validate_params_success():
    """Test parameter validation with valid params."""
    registry = ActionRegistryImpl()
    
    registry.load_from_dict({
        "action_id": "validate.test",
        "category": "test",
        "required_params": ["param1", "param2"],
        "permission_level": "user",
        "risk_level": "low",
        "execution": {},
        "rollback_strategy": "none"
    })
    
    is_valid, missing = registry.validate_params(
        "validate.test",
        {"param1": "value1", "param2": "value2"}
    )
    
    assert is_valid is True
    assert len(missing) == 0
    print("[PASS] test_validate_params_success")


def test_validate_params_missing():
    """Test parameter validation with missing params."""
    registry = ActionRegistryImpl()
    
    registry.load_from_dict({
        "action_id": "validate.test",
        "category": "test",
        "required_params": ["param1", "param2"],
        "permission_level": "user",
        "risk_level": "low",
        "execution": {},
        "rollback_strategy": "none"
    })
    
    is_valid, missing = registry.validate_params(
        "validate.test",
        {"param1": "value1"}
    )
    
    assert is_valid is False
    assert "param2" in missing
    print("[PASS] test_validate_params_missing")


def test_list_actions():
    """Test listing all actions."""
    registry = ActionRegistryImpl()
    
    for i in range(3):
        registry.load_from_dict({
            "action_id": f"action.{i}",
            "category": "test",
            "required_params": [],
            "permission_level": "user",
            "risk_level": "low",
            "execution": {},
            "rollback_strategy": "none"
        })
    
    actions = registry.list_actions()
    assert len(actions) == 3
    assert "action.0" in actions
    assert "action.2" in actions
    print("[PASS] test_list_actions")


def test_get_by_category():
    """Test getting actions by category."""
    registry = ActionRegistryImpl()
    
    registry.load_from_dict({
        "action_id": "file.read",
        "category": "file",
        "required_params": [],
        "permission_level": "user",
        "risk_level": "low",
        "execution": {},
        "rollback_strategy": "none"
    })
    
    registry.load_from_dict({
        "action_id": "system.info",
        "category": "system",
        "required_params": [],
        "permission_level": "user",
        "risk_level": "low",
        "execution": {},
        "rollback_strategy": "none"
    })
    
    file_actions = registry.get_by_category("file")
    assert len(file_actions) == 1
    assert file_actions[0].action_id == "file.read"
    print("[PASS] test_get_by_category")


def test_example_actions():
    """Test loading example action files."""
    registry = ActionRegistryImpl()
    
    # Get correct path relative to project root
    actions_dir = Path(__file__).parent.parent / "unishell" / "core" / "action_registry" / "actions"
    
    # Load individual JSON files
    registry.load_from_file(str(actions_dir / "file.move.json"))
    registry.load_from_file(str(actions_dir / "file.delete.json"))
    registry.load_from_file(str(actions_dir / "system.restart.json"))
    
    assert len(registry.list_actions()) == 3
    
    # Check file.move
    file_move = registry.get_action("file.move")
    assert file_move.risk_level == RiskLevel.MEDIUM
    assert file_move.rollback_strategy == RollbackStrategy.AUTOMATIC
    assert "source" in file_move.required_params
    assert "destination" in file_move.required_params
    
    # Check file.delete
    file_delete = registry.get_action("file.delete")
    assert file_delete.risk_level == RiskLevel.HIGH
    assert file_delete.rollback_strategy == RollbackStrategy.CHECKPOINT
    
    # Check system.restart
    system_restart = registry.get_action("system.restart")
    assert system_restart.risk_level == RiskLevel.CRITICAL
    assert system_restart.permission_level == PermissionLevel.ADMIN
    
    print("[PASS] test_example_actions")


def test_yaml_loading():
    """Test loading from YAML file."""
    registry = ActionRegistryImpl()
    
    # Get correct path relative to project root
    actions_dir = Path(__file__).parent.parent / "unishell" / "core" / "action_registry" / "actions"
    registry.load_from_file(str(actions_dir / "example_actions.yaml"))
    
    assert len(registry.list_actions()) == 3
    assert "file.move" in registry.list_actions()
    assert "file.delete" in registry.list_actions()
    assert "system.restart" in registry.list_actions()
    
    print("[PASS] test_yaml_loading")


if __name__ == "__main__":
    print("Running ActionRegistry tests...\n")
    
    try:
        test_load_from_json()
        test_load_from_dict()
        test_validate_params_success()
        test_validate_params_missing()
        test_list_actions()
        test_get_by_category()
        test_example_actions()
        test_yaml_loading()
        
        print("\n[SUCCESS] All tests passed!")
    except AssertionError as e:
        print(f"\n[FAIL] Test failed: {e}")
        raise
    except Exception as e:
        print(f"\n[ERROR] {e}")
        raise
