import json
import os


class UserStore:
    def __init__(self, path: str):
        self._path = path

    def _load(self) -> dict:
        if not os.path.exists(self._path):
            return {"active": None, "users": {}}
        with open(self._path) as f:
            return json.load(f)

    def _save(self, data: dict) -> None:
        with open(self._path, "w") as f:
            json.dump(data, f, indent=2)

    def add(self, name: str, privkey_hex: str, pubkey_hex: str) -> str:
        data = self._load()
        if name in data["users"]:
            return f"Użytkownik '{name}' już istnieje."
        data["users"][name] = {"privkey": privkey_hex, "pubkey": pubkey_hex}
        if data["active"] is None:
            data["active"] = name
        self._save(data)
        return f"Dodano użytkownika '{name}'.\npubkey: {pubkey_hex}"

    def switch(self, name: str) -> str:
        data = self._load()
        if name not in data["users"]:
            raise ValueError(f"Użytkownik '{name}' nie istnieje.")
        data["active"] = name
        self._save(data)
        return f"Aktywny użytkownik: '{name}'\npubkey: {data['users'][name]['pubkey']}"

    def list_all(self) -> str:
        data = self._load()
        if not data["users"]:
            return "Brak użytkowników."
        lines = []
        for name, u in data["users"].items():
            marker = " ← aktywny" if name == data["active"] else ""
            lines.append(f"{name}{marker}\n  pubkey: {u['pubkey']}")
        return "\n".join(lines)

    def get_active(self) -> tuple[str, dict]:
        data = self._load()
        active = data.get("active")
        if not active or active not in data["users"]:
            raise ValueError("Brak aktywnego użytkownika. Użyj add_user lub switch_user.")
        return active, data["users"][active]
