# cache.py — last known quotes, exchange rates and request budgets on disk
#
# Lets the app open with the last prices it saw, and keep showing them
# when the data source is down or rate-limiting.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import json
import os
from pathlib import Path

from .providers.base import Quote


def cache_dir():
    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(Path.home(), ".cache")
    return Path(base) / "gnome-portfolio"


class QuoteCache:
    VERSION = 1

    def __init__(self, path=None):
        self.path = Path(path) if path else cache_dir() / "quotes.json"

    def load(self):
        """Returns (quotes, rates, budgets); empty on any problem."""
        try:
            doc = json.loads(self.path.read_text(encoding="utf-8"))
            if doc.get("version") != self.VERSION:
                return {}, {}, {}
            quotes = {s: Quote.from_dict(q) for s, q in doc.get("quotes", {}).items()}
            rates = {pair: tuple(v) for pair, v in doc.get("rates", {}).items()}
            return quotes, rates, doc.get("budgets", {})
        except (OSError, ValueError, TypeError, KeyError):
            return {}, {}, {}

    def save(self, quotes, rates, budgets):
        try:
            self.path.parent.mkdir(parents=True, exist_ok=True)
            doc = {"version": self.VERSION,
                   "quotes": {s: q.to_dict() for s, q in quotes.items()},
                   "rates": {pair: list(v) for pair, v in rates.items()},
                   "budgets": budgets}
            tmp = self.path.with_suffix(".tmp")
            tmp.write_text(json.dumps(doc, ensure_ascii=False), encoding="utf-8")
            os.replace(tmp, self.path)
        except OSError:
            pass   # a cache that cannot be written is not worth bothering the user
