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


@dataclass
class Config:
    provider: str = ""
    hetzner_token: str = ""
    server_id: int = 0
    server_ip: str = ""
    ssh_key_path: str = ""
    api_token: str = ""
    user_email: str = ""


def config_dir() -> Path:
    return Path.home() / ".sixtysix"


def data_dir() -> Path:
    return config_dir() / "data"


def config_path() -> Path:
    return config_dir() / "config.json"


def load() -> Config:
    path = config_path()
    if not path.exists():
        return Config()
    try:
        data = json.loads(path.read_text())
        fields = Config.__dataclass_fields__
        return Config(**{k: v for k, v in data.items() if k in fields})
    except Exception:
        return Config()


def save(cfg: Config) -> None:
    config_dir().mkdir(mode=0o700, parents=True, exist_ok=True)
    path = config_path()
    data = {k: v for k, v in asdict(cfg).items() if v}
    path.write_text(json.dumps(data, indent=2))
    path.chmod(0o600)
