from pathlib import Path
import json
from typing import Dict, Optional

_DEFAULT_PATH = Path.home() / ".pyucc_settings.json"


def _read_file(path: Path) -> Dict:
    if not path.exists():
        return {}
    try:
        with path.open("r", encoding="utf-8") as fh:
            data = json.load(fh)
            if isinstance(data, dict):
                return data
    except Exception:
        return {}
    return {}


def _write_file(path: Path, data: Dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=2, ensure_ascii=False)


def load_settings(path: Optional[Path] = None) -> Dict:
    p = path or _DEFAULT_PATH
    return _read_file(p)


def save_settings(data: Dict, path: Optional[Path] = None) -> None:
    p = path or _DEFAULT_PATH
    _write_file(p, data)


def get_baseline_dir() -> Optional[str]:
    s = load_settings()
    return s.get("baseline_dir")


def get_max_keep() -> int:
    s = load_settings()
    try:
        v = int(s.get("max_keep", 5))
    except Exception:
        v = 5
    return v


def set_baseline_settings(baseline_dir: Optional[str], max_keep: int) -> None:
    s = load_settings()
    if baseline_dir is not None:
        s["baseline_dir"] = baseline_dir
    s["max_keep"] = int(max_keep)
    save_settings(s)
