import json
import time
import logging
from pathlib import Path
from platformdirs import user_data_dir

logger = logging.getLogger(__name__)

DATA_DIR = Path(user_data_dir(
    "Jimlet",
    "Jimlet",
    roaming=False,
))

class Stats:

    first_run: int
    num_runs: int

    def __init__(self):

        self.path = DATA_DIR / "stats.json"
        self.first_run = int(time.time())
        self.num_runs = 0

        self.load()
        self.num_runs += 1
        self.save()

        self._initialized = True

    def load(self) -> None:
        if not self.path.exists():
            return

        try:
            data = json.loads(self.path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError):
            return

        first_run = data.get("first_run")
        num_runs = data.get("num_runs")

        if isinstance(first_run, int):
            self.first_run = first_run

        if isinstance(num_runs, int):
            self.num_runs = num_runs

    def save(self) -> None:
        DATA_DIR.mkdir(parents=True, exist_ok=True)
        data = {
            "first_run": self.first_run,
            "num_runs": self.num_runs,
        }
        self.path.write_text(
            json.dumps(data, indent=4),
            encoding="utf-8",
        )


stats = Stats()
