# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
"""App settings stored in ~/.config/hyprsunset-qt/config (INI)."""

from __future__ import annotations

import configparser
from dataclasses import dataclass
from pathlib import Path

SETTINGS_PATH = Path.home() / ".config" / "hyprsunset-qt" / "config"
DEFAULT_CACHE = "~/.config/hyprsunset-qt/sun.json"


@dataclass
class Settings:
    lat: str = ""
    lon: str = ""
    auto_detect: bool = True
    cache_path: str = DEFAULT_CACHE
    daemon_command: str = "hyprsunset"

    @classmethod
    def load(cls, path: Path = SETTINGS_PATH) -> "Settings":
        path = Path(path)
        if not path.exists():
            s = cls()
            s.save(path)
            return s
        cp = configparser.ConfigParser()
        cp.read(path)
        return cls(
            lat=cp.get("location", "lat", fallback=""),
            lon=cp.get("location", "lon", fallback=""),
            auto_detect=cp.getboolean("location", "auto_detect", fallback=True),
            cache_path=cp.get("cache", "path", fallback=DEFAULT_CACHE),
            daemon_command=cp.get("daemon", "command", fallback="hyprsunset"),
        )

    def save(self, path: Path = SETTINGS_PATH) -> None:
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        cp = configparser.ConfigParser()
        cp["location"] = {
            "lat": self.lat,
            "lon": self.lon,
            "auto_detect": str(self.auto_detect).lower(),
        }
        cp["cache"] = {"path": self.cache_path}
        cp["daemon"] = {"command": self.daemon_command}
        with path.open("w") as f:
            cp.write(f)

    def cache_path_expanded(self) -> Path:
        return Path(self.cache_path).expanduser()
