from __future__ import annotations

import json
import logging
import os
from dataclasses import asdict, dataclass
from pathlib import Path

logger = logging.getLogger(__name__)

DEFAULT_CLIENT_CONFIG = Path(
    os.environ.get("SITEDROP_CLIENT_CONFIG", Path.home() / ".sitedroprc")
)


@dataclass
class ClientConfig:
    server_url: str = ""
    token: str = ""
    password: str = ""

    def save(self, path: Path = DEFAULT_CLIENT_CONFIG) -> None:
        path.write_text(json.dumps(asdict(self), indent=2))
        os.chmod(path, 0o600)

    @classmethod
    def load(cls, path: Path = DEFAULT_CLIENT_CONFIG) -> ClientConfig:
        if not path.exists():
            return cls()
        try:
            data = json.loads(path.read_text())
        except (json.JSONDecodeError, OSError) as e:
            logger.warning("Failed to load client config from %s: %s", path, e)
            return cls()
        return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
