"""Sacred Boundary enforcement: trust-level runtime gating for worker tools.

Maps trust levels to permitted tool sets. Called before every tool dispatch.
Closes Gap 5 from ethics audit: trust levels tracked but never enforced.
"""
import re
from pulse.core.autonomy_state import get_trust_level

# Level -> permitted tools (cumulative: higher levels inherit lower)
_LEVEL_PERMISSIONS = {
    0: frozenset([
        "read_file", "list_files", "search_code", "brain_query",
        "complete_task",
    ]),
    1: frozenset([
        "read_file", "list_files", "search_code", "brain_query",
        "complete_task", "extract_knowledge_batch",
        "clean_intents_batch", "check_antipattern",
    ]),
    2: frozenset([
        "read_file", "list_files", "search_code", "brain_query",
        "complete_task", "extract_knowledge_batch",
        "clean_intents_batch", "check_antipattern",
        "write_file", "edit_file", "run_command",
    ]),
    3: frozenset([
        "read_file", "list_files", "search_code", "brain_query",
        "complete_task", "extract_knowledge_batch",
        "clean_intents_batch", "check_antipattern",
        "write_file", "edit_file", "run_command",
        "submit_task",
    ]),
}

# Safety-critical paths that no worker can write to (regardless of trust level)
IMMUTABLE_PATHS = (
    re.compile(r"(?i)corpus_callosum[/\\]"),
    re.compile(r"(?i)pulse[/\\]daemons[/\\]compliance_validator\.py"),
    re.compile(r"(?i)pulse[/\\]core[/\\]pulse_crypto\.py"),
    re.compile(r"(?i)pulse[/\\]core[/\\]pii_filter\.py"),
    re.compile(r"(?i)pulse[/\\]core[/\\]trust_gate\.py"),
    re.compile(r"(?i)pulse[/\\]core[/\\]autonomy_state\.py"),
    re.compile(r"(?i)pulse[/\\]workers[/\\]runner[/\\]worker_compliance\.py"),
    re.compile(r"(?i)state[/\\]quarantined_entities\.json"),
    re.compile(r"(?i)state[/\\]autonomy_state\.json"),
)


def check_trust(tool_name: str, args: dict) -> tuple[bool, str]:
    """Check if current trust level permits this tool + arguments.

    Returns (permitted, reason). Reason is empty string if permitted.
    """
    level = get_trust_level()
    permitted = _LEVEL_PERMISSIONS.get(min(level, 3), _LEVEL_PERMISSIONS[0])

    if tool_name not in permitted:
        return False, f"TRUST_GATE:level_{level}_cannot_use_{tool_name}"

    # Immutable path check for write operations
    if tool_name in ("write_file", "edit_file"):
        path = (args.get("path", "") or "").replace("\\", "/")
        for pattern in IMMUTABLE_PATHS:
            if pattern.search(path):
                return False, f"SACRED_BOUNDARY:immutable_path:{path}"

    return True, ""
