import atexit
import time
import os
from .security import generate_signature
from .transporter import Transporter
class Gatekeeper:
    def __init__(self, bunker_url: str = None, secret: str = None, client_id: str = None):
        self.bunker_url = bunker_url or os.getenv("STANLEY_BUNKER_URL", "http://localhost:3000")
        self.secret = secret or os.getenv("STANLEY_HMAC_SECRET")
        self.client_id = client_id or os.getenv("STANLEY_CLIENT_ID")
        
        if not self.secret or not self.client_id:
            raise ValueError("🛡️ Stanley Shield Error: Missing Credentials (ID or Secret)!")
            
        self.transporter = Transporter(self.bunker_url)
        # Ensure logs are sent even if the script ends abruptly
        atexit.register(self.transporter.flush)

    def log(self, actor_id: str, action: str, resource: str, residency: str = "GLOBAL", metadata: dict = None, context: dict = None):
        timestamp = str(int(time.time()))
        
        # ALIGNMENT: This matches the Node.js IAuditPayload exactly
        payload = {
            "clientId": self.client_id,
            "residency": residency,
            "actor": { "id": actor_id, "type": "USER" },
            "action": action,
            "status": "SUCCESS",
            "resource": resource,
            "context": context or { "ip": "127.0.0.1", "userAgent": "stanley-sdk-python" },
            "metadata": metadata or {},
            "timestamp": timestamp
        }

        signature = generate_signature(payload, timestamp, self.secret)
        
        packet = {
            "payload": payload,
            "timestamp": timestamp,
            "signature": signature
        }

        self.transporter.send(packet)