"""Persistenter User-State: Whitelist (immer behalten) + Ignored (nicht mehr anzeigen)."""
from __future__ import annotations

import json
from dataclasses import dataclass, field
from pathlib import Path

from taninux.core.paths import state_file


@dataclass
class State:
    whitelist: set[Path] = field(default_factory=set)
    ignored: set[Path] = field(default_factory=set)

    # ---- load / save ----

    @classmethod
    def load(cls) -> "State":
        f = state_file()
        if not f.exists():
            return cls()
        try:
            data = json.loads(f.read_text())
        except (json.JSONDecodeError, OSError):
            return cls()
        return cls(
            whitelist={Path(p) for p in data.get("whitelist", [])},
            ignored={Path(p) for p in data.get("ignored", [])},
        )

    def save(self) -> None:
        f = state_file()
        payload = {
            "version": 1,
            "whitelist": sorted(str(p) for p in self.whitelist),
            "ignored": sorted(str(p) for p in self.ignored),
        }
        f.write_text(json.dumps(payload, indent=2))

    # ---- queries ----

    def is_whitelisted(self, p: Path) -> bool:
        return p in self.whitelist

    def is_ignored(self, p: Path) -> bool:
        return p in self.ignored

    # ---- mutations (auto-save) ----

    def whitelist_add(self, p: Path) -> None:
        self.whitelist.add(p)
        self.ignored.discard(p)
        self.save()

    def whitelist_remove(self, p: Path) -> None:
        if p in self.whitelist:
            self.whitelist.discard(p)
            self.save()

    def ignore_add(self, p: Path) -> None:
        self.ignored.add(p)
        self.whitelist.discard(p)
        self.save()

    def ignore_remove(self, p: Path) -> None:
        if p in self.ignored:
            self.ignored.discard(p)
            self.save()
