from mesh_core import agent_pb2

class SandboxEngine:
    """Core Security Engine for Local Command Verification."""
    def __init__(self):
        self.policy = None

    def sync(self, p):
        """Syncs the latest policy from the Orchestrator."""
        self.policy = {
            "MODE": "STRICT" if p.mode == agent_pb2.SandboxPolicy.STRICT else "PERMISSIVE",
            "ALLOWED": list(p.allowed_commands), 
            "DENIED": list(p.denied_commands), 
            "SENSITIVE": list(p.sensitive_commands),
            "WORKING_DIR_JAIL": p.working_dir_jail,
            "SKILL_CONFIG": p.skill_config_json
        }

    def verify(self, command_str):
        """Verifies if a command string is allowed under the current policy."""
        if not self.policy: return False, "No Policy"
        
        parts = (command_str or "").strip().split()
        if not parts: return False, "Empty"
        
        # M6 FIX: Strip trailing shell operators (;, &, |, etc) from the base command
        # This prevents "whoami;" from being blocked if "whoami" is whitelisted.
        import re
        base_cmd = re.sub(r'[;&|]+$', '', parts[0])
        
        if base_cmd in self.policy["DENIED"]: 
            return False, f"Forbidden command: {base_cmd}"
            
        if self.policy["MODE"] == "STRICT" and base_cmd not in self.policy["ALLOWED"]:
             return False, f"Command '{base_cmd}' not whitelisted"
             
        return True, "OK"
