"""Desktop API shared secret header (desktopKey) for Workstatus API requests."""

from __future__ import annotations

import hashlib
import hmac
import os
from typing import Any, Dict, Optional

from ws_package.configs.security import Security_config
from ws_package.log.writer import LogWriter

logger = LogWriter.file(__name__)

DESKTOP_KEY_HEADER = "desktopKey"

_cached_desktop_key: Optional[str] = None
_desktop_key_loaded = False
_cached_agent_secret: Optional[str] = None
_agent_secret_loaded = False


def get_desktop_key() -> Optional[str]:
    """Resolve DESKTOP_KEY from env or security.ini [Security] DESKTOP_KEY."""
    global _cached_desktop_key, _desktop_key_loaded
    if _desktop_key_loaded:
        return _cached_desktop_key

    _desktop_key_loaded = True

    from_env = (os.environ.get("DESKTOP_KEY") or "").strip()
    if from_env:
        _cached_desktop_key = from_env
        return from_env

    try:
        from_ini = Security_config("DESKTOP_KEY", "Security")
        if from_ini and str(from_ini).strip():
            _cached_desktop_key = str(from_ini).strip()
            return _cached_desktop_key
    except Exception as e:
        logger.debug("Could not read DESKTOP_KEY from security.ini: %s", e)

    _cached_desktop_key = None
    return None


def get_agent_secret() -> Optional[str]:
    """Resolve HMAC signing secret from env or security.ini [Security] shared_secret."""
    global _cached_agent_secret, _agent_secret_loaded
    if _agent_secret_loaded:
        return _cached_agent_secret

    _agent_secret_loaded = True

    from_env = (os.environ.get("AGENT_SECRET") or os.environ.get("WORKSTATUS_IPC_SECRET") or "").strip()
    if from_env:
        _cached_agent_secret = from_env
        return from_env

    try:
        from_ini = Security_config("shared_secret", "Security")
        if from_ini and str(from_ini).strip():
            _cached_agent_secret = str(from_ini).strip()
            return _cached_agent_secret
    except Exception as e:
        logger.debug("Could not read shared_secret from security.ini: %s", e)

    _cached_agent_secret = None
    return None


def hmac_desktop_key(desktop_key: str, agent_secret: str) -> str:
    """Return HMAC-SHA256 hex digest of the desktop key."""
    return hmac.new(
        agent_secret.encode("utf-8"),
        desktop_key.encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()


def apply_desktop_key(headers: Optional[Dict[str, Any]] = None) -> Dict[str, str]:
    """Merge HMAC-SHA256 signed desktopKey into headers when configured."""
    merged: Dict[str, str] = {}
    if headers:
        merged = {str(k): str(v) for k, v in headers.items() if v is not None}

    desktop_key = get_desktop_key()
    if not desktop_key:
        return merged

    agent_secret = get_agent_secret()
    if agent_secret:
        merged[DESKTOP_KEY_HEADER] = hmac_desktop_key(desktop_key, agent_secret)
    else:
        logger.debug("DESKTOP_KEY configured but agent secret missing; sending raw desktopKey")
        merged[DESKTOP_KEY_HEADER] = desktop_key

    return merged


def api_headers(extra: Optional[Dict[str, Any]] = None) -> Dict[str, str]:
    """Build API request headers with signed desktopKey included."""
    return apply_desktop_key(extra)
