import re
from typing import Dict

# edited by glg


class PrinterSettingsValueService:
    @staticmethod
    def to_non_negative_int(value, default=0):
        try:
            parsed = int(float(value))
        except (TypeError, ValueError, KeyError, AttributeError, RuntimeError, OSError, LookupError, ArithmeticError, ImportError):
            parsed = int(default or 0)
        return parsed if parsed > 0 else 0

    @staticmethod
    def extract_point_from_diskon_log(diskon_log: str) -> int:
        text = str(diskon_log or "").strip()
        if not text:
            return 0
        match = re.search(r"(?:^|;)point=([^;]*)", text)
        if not match:
            return 0
        return PrinterSettingsValueService.to_non_negative_int(match.group(1), 0)

    @staticmethod
    def resolve_point_transaksi_value(transaksi_data_dict: Dict) -> int:
        data = transaksi_data_dict if isinstance(transaksi_data_dict, dict) else {}
        direct = PrinterSettingsValueService.to_non_negative_int(data.get("point_transaksi"), 0)
        if direct > 0:
            return direct
        alt = PrinterSettingsValueService.to_non_negative_int(data.get("point_nilai"), 0)
        if alt > 0:
            return alt
        return PrinterSettingsValueService.extract_point_from_diskon_log(data.get("diskon_log"))

    @staticmethod
    def normalize_ppn_mode(value: str, default: str = "exclude") -> str:
        mode = str(value or "").strip().lower()
        if mode in {"include", "exclude"}:
            return mode
        return str(default or "exclude").strip().lower() or "exclude"

    @staticmethod
    def extract_ppn_mode_from_diskon_log(diskon_log: str) -> str:
        text = str(diskon_log or "").strip().lower()
        if not text:
            return ""
        match = re.search(r"(?:^|;)ppn_mode=([^;]*)", text)
        if not match:
            return ""
        mode = str(match.group(1) or "").strip().lower()
        return mode if mode in {"include", "exclude"} else ""

    @staticmethod
    def resolve_ppn_mode(transaksi_data_dict: Dict) -> str:
        data = transaksi_data_dict if isinstance(transaksi_data_dict, dict) else {}
        mode = str(data.get("ppn_mode") or "").strip().lower()
        if mode in {"include", "exclude"}:
            return mode
        from_log = PrinterSettingsValueService.extract_ppn_mode_from_diskon_log(data.get("diskon_log"))
        return PrinterSettingsValueService.normalize_ppn_mode(from_log, default="exclude")
