import logging
import time
from pathlib import Path
import json


class CrashProcessor:
    def __init__(self, config_path="config.json"):
        self.logger = logging.getLogger("CrashProcessor")

        with open(config_path, "r", encoding="utf-8") as file:
            self.config = json.load(file)

        self.data_dir = Path(
            self.config["capture"]["data_directory"]
        )
        self.data_dir.mkdir(parents=True, exist_ok=True)

        self.history_file = self.data_dir / "crash_history.json"

        self.history = self._load_history()

        self.current_round = None

    def _load_history(self):
        if not self.history_file.exists():
            return []

        try:
            with open(
                self.history_file,
                "r",
                encoding="utf-8"
            ) as file:
                return json.load(file)

        except (json.JSONDecodeError, OSError):
            return []

    def _save_history(self):
        with open(
            self.history_file,
            "w",
            encoding="utf-8"
        ) as file:
            json.dump(
                self.history,
                file,
                indent=2,
                ensure_ascii=False
            )

    def process(self, packet):
        """
        Receives decoded protocol packets.

        This layer deliberately does not assume that every
        binary packet is a Crash result. The actual protobuf/
        binary field decoding will be added once the captured
        message structure is mapped.
        """

        if not packet:
            return None

        if packet.get("type") not in (
            "socket_event",
            "socket_binary_event"
        ):
            return None

        return self._inspect_packet(packet)

    def _inspect_packet(self, packet):
        event = {
            "timestamp": time.time(),
            "packet_type": packet.get("type"),
            "length": packet.get("length"),
            "raw": packet.get("hex")
        }

        payload = packet.get("payload")

        if payload is not None:
            event["payload"] = payload

        self.current_round = event

        return event

    def record_result(self, multiplier):
        """
        Stores a confirmed Crash result.

        The value is only recorded when supplied by the
        decoded game event; this system does not invent
        or estimate historical results here.
        """

        try:
            multiplier = float(multiplier)
        except (TypeError, ValueError):
            return False

        result = {
            "timestamp": time.time(),
            "multiplier": multiplier
        }

        self.history.append(result)

        # Keep the local dataset manageable.
        if len(self.history) > 10000:
            self.history = self.history[-10000:]

        self._save_history()

        return True

    def get_history(self, limit=100):
        return self.history[-limit:]

    def get_latest(self):
        if not self.history:
            return None

        return self.history[-1]

    def get_count(self):
        return len(self.history)