"""Tests for agent authentication and RBAC."""

import os

import pytest

from loom.auth.models import Agent, AgentRole, ROLE_PERMISSIONS
from loom.auth.store import authenticate, create_agent, deactivate_agent, list_agents
from loom.auth.middleware import check_permission, is_auth_enabled


async def test_create_agent(pool):
    agent = await create_agent(pool, "test-worker", "worker", "secret-key-123")
    assert agent.name == "test-worker"
    assert agent.role == AgentRole.WORKER
    assert agent.active is True


async def test_authenticate_valid_key(pool):
    await create_agent(pool, "auth-test", "worker", "my-api-key")
    agent = await authenticate(pool, "my-api-key")
    assert agent is not None
    assert agent.name == "auth-test"
    assert agent.last_seen_at is not None


async def test_authenticate_invalid_key(pool):
    await create_agent(pool, "auth-test", "worker", "correct-key")
    agent = await authenticate(pool, "wrong-key")
    assert agent is None


async def test_role_permissions_readonly():
    agent = Agent(id="a1", name="readonly", role=AgentRole.READONLY)
    assert check_permission(agent, "loom_ready", "p1") is True
    assert check_permission(agent, "loom_claim", "p1") is False
    assert check_permission(agent, "loom_create", "p1") is False


async def test_role_permissions_worker():
    agent = Agent(id="a2", name="worker", role=AgentRole.WORKER)
    assert check_permission(agent, "loom_claim", "p1") is True
    assert check_permission(agent, "loom_done", "p1") is True
    assert check_permission(agent, "loom_create", "p1") is False


async def test_role_permissions_lead():
    agent = Agent(id="a3", name="lead", role=AgentRole.LEAD)
    assert check_permission(agent, "loom_create", "p1") is True
    assert check_permission(agent, "loom_decompose", "p1") is True
    assert check_permission(agent, "loom_create_project", "p1") is False


async def test_role_permissions_admin():
    agent = Agent(id="a4", name="admin", role=AgentRole.ADMIN)
    assert check_permission(agent, "loom_create_project", "p1") is True
    assert check_permission(agent, "loom_archive_project", "p1") is True


async def test_project_scope_enforcement():
    agent = Agent(id="a5", name="scoped", role=AgentRole.WORKER, project_ids=["proj-1"])
    assert check_permission(agent, "loom_claim", "proj-1") is True
    assert check_permission(agent, "loom_claim", "proj-2") is False


async def test_auth_disabled_by_default():
    """Without LOOM_AUTH_ENABLED, auth should be off."""
    old = os.environ.pop("LOOM_AUTH_ENABLED", None)
    try:
        assert is_auth_enabled() is False
    finally:
        if old is not None:
            os.environ["LOOM_AUTH_ENABLED"] = old


async def test_auth_enabled_requires_key(monkeypatch):
    monkeypatch.setenv("LOOM_AUTH_ENABLED", "true")
    assert is_auth_enabled() is True


async def test_deactivate_agent(pool):
    agent = await create_agent(pool, "to-deactivate", "worker", "key-123")
    await deactivate_agent(pool, agent.id)
    result = await authenticate(pool, "key-123")
    assert result is None


async def test_list_agents(pool):
    await create_agent(pool, "agent-1", "worker", "key-1")
    await create_agent(pool, "agent-2", "lead", "key-2")
    agents = await list_agents(pool)
    names = {a.name for a in agents}
    assert "agent-1" in names
    assert "agent-2" in names
