import json
from pathlib import Path
from .exceptions import ChatException
from .logger import get_logger

logger = get_logger(f"dracula.{__name__}")


class Stats:
    def __init__(self, filepath: str = "dracula_stats.json"):
        self.filepath = Path(filepath)
        self.total_messages = 0
        self.total_responses = 0
        self.total_characters_sent = 0
        self.total_characters_received = 0
        self._load()

    def _load(self):
        try:
            if self.filepath.exists():

                data = json.loads(self.filepath.read_text(encoding="utf-8"))
                self.total_messages = data.get("total_messages", 0)
                self.total_responses = data.get("total_responses", 0)
                self.total_characters_sent = data.get("total_characters_sent", 0)
                self.total_characters_received = data.get(
                    "total_characters_received", 0
                )
                logger.debug("Stats loaded successfully.")

        except Exception as e:
            raise ChatException(f"Failed to load stats: {str(e)}")

    def _save(self):
        try:
            self.filepath.parent.mkdir(parents=True, exist_ok=True)
            self.filepath.write_text(
                json.dumps(self.get_stats(), indent=4), encoding="utf-8"
            )
            logger.debug("Stats saved successfully.")

        except Exception as e:
            raise ChatException(f"Failed to save stats: {str(e)}")

    def record_message(self, message: str):
        self.total_messages += 1
        self.total_characters_sent += len(message)
        self._save()

    def record_response(self, response: str):
        self.total_responses += 1
        self.total_characters_received += len(response)
        self._save()

    def get_stats(self) -> dict:
        return {
            "total_messages": self.total_messages,
            "total_responses": self.total_responses,
            "total_characters_sent": self.total_characters_sent,
            "total_characters_received": self.total_characters_received,
        }

    def reset(self):
        self.total_messages = 0
        self.total_responses = 0
        self.total_characters_sent = 0
        self.total_characters_received = 0
        logger.info("Stats reset.")
        self._save()
