from __future__ import annotations

from datetime import datetime, timezone
import json
from pathlib import Path


REDACTED = "[REDACTED]"
SENSITIVE_KEY_PARTS = (
    "token",
    "secret",
    "signature",
    "auth",
    "password",
)


class DesktopAgentEventLogger:
    """Append-only local logger with sensitive-field redaction."""

    def __init__(self, log_path: str | Path) -> None:
        self._log_path = Path(log_path)

    @property
    def log_path(self) -> Path:
        return self._log_path

    def log(self, event: str, fields: dict[str, object] | None = None) -> None:
        sanitized_fields = self.sanitize_fields(fields or {})
        payload = {
            "timestamp": datetime.now(tz=timezone.utc).isoformat(),
            "event": str(event),
            "fields": sanitized_fields,
        }
        self._log_path.parent.mkdir(parents=True, exist_ok=True)
        with self._log_path.open("a", encoding="utf-8") as handle:
            handle.write(json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")))
            handle.write("\n")

    @classmethod
    def sanitize_fields(cls, fields: dict[str, object]) -> dict[str, object]:
        sanitized: dict[str, object] = {}
        for key, value in fields.items():
            normalized_key = str(key).strip().lower()
            if any(part in normalized_key for part in SENSITIVE_KEY_PARTS):
                sanitized[str(key)] = REDACTED
                continue
            sanitized[str(key)] = value
        return sanitized
