# edited by glg
import json
from typing import Any, Dict


class TransactionExportPayloadCompressionService:
    def __init__(self, logger=None):
        self._logger = logger

    def _log_warning(self, message, *args):
        logger = self._logger
        if logger is None:
            return
        try:
            logger.warning(message, *args)
        except Exception:
            return

    def resolve_export_compression(self, config: Dict[str, Any]) -> str:
        raw_codec = str((config or {}).get("export_compression_codec") or "xz").strip().lower()
        if raw_codec in {"xz", "gz"}:
            return raw_codec
        self._log_warning(
            "[DEBUG EXPORT] codec export tidak dikenali: %s, fallback ke xz",
            raw_codec,
        )
        return "xz"

    def write_compressed_payload(self, tmp_path: str, payload: Any, codec: str, config: Dict[str, Any]):
        if str(codec or "").strip().lower() == "xz":
            try:
                import lzma
            except (ImportError, ModuleNotFoundError) as exc:
                raise RuntimeError(
                    "Codec xz tidak tersedia di runtime Python ini. "
                    "Pasang dukungan lzma atau ubah export_compression_codec ke 'gz'."
                ) from exc
            try:
                preset = int((config or {}).get("export_xz_preset") or 6)
            except (TypeError, ValueError):
                preset = 6
            preset = max(0, min(9, preset))
            with lzma.open(tmp_path, "wt", encoding="utf-8", preset=preset) as handle:
                json.dump(payload, handle, ensure_ascii=False, separators=(",", ":"))
            return

        import gzip

        with gzip.open(tmp_path, "wt", encoding="utf-8") as handle:
            json.dump(payload, handle, ensure_ascii=False, separators=(",", ":"))
