"""
Engineer interface and simple token mechanism.

This module provides:
 - a way to request an engineer override token (simulated)
 - token validation for soft lockdown bypass
 - NOTE: This is a simulation. In production, use strong authentication (MFA), PKI certificates,
   or HSM-backed signing of short-lived tokens.
"""
import time
import secrets
import logging

logger = logging.getLogger(__name__)

class EngineerTokenError(Exception):
    pass

class EngineerInterface:
    # simple in-memory token store for demo
    _token_store = {}

    TOKEN_TTL = 60.0  # seconds

    @classmethod
    def request_engineer_token(cls, engineer_id: str) -> str:
        """
        Simulates an authenticated engineer requesting an override token.
        In real systems this requires strong auth and auditing.
        """
        if not engineer_id:
            raise EngineerTokenError("engineer_id_required")
        token = secrets.token_hex(16)
        expiry = time.time() + cls.TOKEN_TTL
        cls._token_store[token] = {"engineer_id": engineer_id, "expiry": expiry}
        logger.info("Issued engineer token for %s valid for %.0f seconds", engineer_id, cls.TOKEN_TTL)
        return token

    @classmethod
    def validate_token(cls, token: str) -> bool:
        if not token:
            return False
        rec = cls._token_store.get(token)
        if not rec:
            return False
        if time.time() > rec["expiry"]:
            # token expired: remove
            del cls._token_store[token]
            return False
        return True

    @staticmethod
    def is_engineer_payload(payload: dict) -> bool:
        """
        Detect whether a control payload is intended as an engineer override.
        We use a reserved "token" field in the payload to distinguish.
        """
        return isinstance(payload, dict) and "token" in payload
