"""Agent Profile v1 validation and tool filtering checks."""

from __future__ import annotations

import sys
import unittest
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))
loaded_platform = sys.modules.get("platform")
if loaded_platform is not None and not hasattr(loaded_platform, "__path__"):
    del sys.modules["platform"]

from bridge_platform.agents.profiles import AgentProfileContract, filter_profile_tools


def profile(**overrides):
    values = {
        "agent_key": "test_assistant",
        "name": "Test Assistant",
        "version": "1.0.0",
        "instructions_version": "1.0.0",
        "description": "Profile contract test.",
        "allowed_capabilities": ("records.read",),
    }
    values.update(overrides)
    return AgentProfileContract(**values)


class AgentProfileChecks(unittest.TestCase):
    def test_single_app_profile_filters_other_tools(self):
        tools = [
            {"capability": "records.read", "risk": {"category": "read"}, "confirmation": "never"},
            {"capability": "invoices.extract", "risk": {"category": "read"}, "confirmation": "never"},
        ]
        filtered = filter_profile_tools(profile(), tools)
        self.assertEqual(["records.read"], [tool["capability"] for tool in filtered])

    def test_multi_app_profile_keeps_available_allowed_tools_only(self):
        contract = profile(allowed_capabilities=("records.read", "invoices.extract", "future.tool"))
        tools = [
            {"capability": "records.read", "risk": {"category": "read"}, "confirmation": "never"},
            {"capability": "invoices.extract", "risk": {"category": "read"}, "confirmation": "never"},
        ]
        self.assertEqual(2, len(filter_profile_tools(contract, tools)))

    def test_profile_can_only_make_confirmation_stricter(self):
        contract = profile(confirmation_policy={"write_reversible": "always"})
        tool = {
            "capability": "records.read", "risk": {"category": "write_reversible"},
            "confirmation": "policy",
        }
        self.assertEqual("always", filter_profile_tools(contract, [tool])[0]["confirmation"])

    def test_invalid_profile_limits_and_capabilities_are_rejected(self):
        errors = profile(allowed_capabilities=("Bad Capability",), max_steps=0).validate()
        self.assertTrue(any("capability" in error for error in errors))
        self.assertTrue(any("max_steps" in error for error in errors))


if __name__ == "__main__":
    unittest.main(verbosity=2)
