"""Test permission-based tool registration.

This script verifies that:
1. Tools with @public are always registered
2. Tools with @requires_permissions are only registered if user has permissions
3. ptAdmin gets all tools
4. Unauthenticated users only get @public tools
"""

from point_topic_mcp.auth.decorators import (
    public,
    requires_permissions,
    PUBLIC_TOOLS,
    TOOL_PERMISSIONS,
)
from point_topic_mcp.auth.middleware import is_pt_admin


# Simulate different user permission scenarios
def test_registration_scenario(user_permissions, user_type):
    """Test which tools would be registered for a specific user."""
    print(f"\n{'=' * 60}")
    print(f"Testing: {user_type}")
    print(f"Permissions: {user_permissions if user_permissions else 'None'}")
    print(f"{'=' * 60}")

    is_admin = is_pt_admin(user_permissions)
    is_authenticated = len(user_permissions) > 0

    available_tools = []

    # Check all registered decorators
    for tool_name in list(PUBLIC_TOOLS) + list(TOOL_PERMISSIONS.keys()):
        # Skip duplicates
        if tool_name in [t for t, _ in available_tools]:
            continue

        is_public = tool_name in PUBLIC_TOOLS
        required_perms = TOOL_PERMISSIONS.get(tool_name, [])

        # Check if tool should be registered
        should_register = False
        reason = ""

        if is_public:
            should_register = True
            reason = "@public decorator"
        elif is_admin:
            should_register = True
            reason = "ptAdmin - all tools"
        elif is_authenticated:
            if not required_perms:
                should_register = True
                reason = "Authenticated - no permission requirements"
            else:
                # Check if user has ALL required permissions
                has_all = all(p in user_permissions for p in required_perms)
                if has_all:
                    should_register = True
                    reason = f"Has permissions: {required_perms}"
                else:
                    missing = [p for p in required_perms if p not in user_permissions]
                    reason = f"Missing: {missing}"
        else:
            reason = "Authentication required"

        if should_register:
            available_tools.append((tool_name, reason))
            print(f"  ✅ {tool_name}: {reason}")
        else:
            print(f"  ❌ {tool_name}: {reason}")

    return available_tools


# Test scenarios
print("\n" + "=" * 60)
print("PERMISSION-BASED TOOL REGISTRATION TESTS")
print("=" * 60)

# Scenario 1: Unauthenticated user
unauthenticated = test_registration_scenario([], "Unauthenticated User")
print(f"\nResult: {len(unauthenticated)} tools available")

# Scenario 2: Regular authenticated user (no special permissions)
regular_user = test_registration_scenario(
    ["user:upc-query-agent"], "Regular User (user:upc-query-agent)"
)
print(f"\nResult: {len(regular_user)} tools available")

# Scenario 3: ptAdmin
admin_user = test_registration_scenario(["ptAdmin"], "ptAdmin User")
print(f"\nResult: {len(admin_user)} tools available")

# Summary
print("\n" + "=" * 60)
print("SUMMARY")
print("=" * 60)
print(f"Unauthenticated: {len(unauthenticated)} tools")
print(f"Regular User:    {len(regular_user)} tools")
print(f"ptAdmin:         {len(admin_user)} tools")

if len(admin_user) >= len(regular_user) >= len(unauthenticated):
    print("\n✅ Permission hierarchy working correctly!")
else:
    print("\n❌ Error: Unexpected permission hierarchy")
