"""Auth enforcement middleware for MCP tools."""

from __future__ import annotations

import os

from loom.auth.models import Agent, ROLE_PERMISSIONS


def check_permission(
    agent: Agent | None,
    tool_name: str,
    project_id: str = "",
) -> bool:
    """Check if agent has permission to use the tool on the given project."""
    if agent is None:
        return False

    # Check role permissions
    allowed_tools = ROLE_PERMISSIONS.get(agent.role.value, set())
    if tool_name not in allowed_tools:
        return False

    # Check project scope (empty means all projects)
    if agent.project_ids and project_id:
        if project_id not in agent.project_ids:
            return False

    return True


def is_auth_enabled() -> bool:
    """Check if auth is enabled via environment variable or config."""
    return os.environ.get("LOOM_AUTH_ENABLED", "").lower() in ("true", "1", "yes")
