"""App settings persisted in data/settings.json (editable from UI)."""

from __future__ import annotations

import json
from pathlib import Path

from epochler.config import get_settings


def _settings_path() -> Path:
    return get_settings().data_dir / "settings.json"


def get_app_settings() -> dict:
    """Load app settings from data/settings.json. Falls back to config/env."""
    path = _settings_path()
    if path.exists():
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            return dict(data)
        except (json.JSONDecodeError, OSError):
            pass
    return {}


def save_app_settings(updates: dict) -> dict:
    """Merge updates into settings and persist to data/settings.json."""
    path = _settings_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    current = get_app_settings()
    current.update(updates)
    path.write_text(json.dumps(current, indent=2), encoding="utf-8")
    return current


def get_workspace_root() -> Path | None:
    """Effective workspace root: UI settings > env/config > None."""
    app = get_app_settings()
    raw = app.get("workspace_root")
    if raw and isinstance(raw, str) and raw.strip():
        return Path(raw.strip()).expanduser().resolve()
    return get_settings().workspace_root
