import json
import os
from .exceptions import ChatException


class Stats:
    def __init__(self, filepath: str = "dracula_stats.json"):
        self.filepath = 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 os.path.exists(self.filepath):
                with open(self.filepath, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    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
                    )

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

    def _save(self):
        try:
            with open(self.filepath, "w", encoding="utf-8") as f:
                json.dump(self.get_stats(), f, indent=4)

        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
        self._save()
