"""
Load/save .dryft/config.json and ensure .dryft directory exists.
"""

import json
from pathlib import Path

# PRD §8.3: default 5 seconds for near-real-time awareness
DEFAULT_POLL_INTERVAL_MS = 5_000
CONFIG_FILENAME = "config.json"
DRYFT_DIR = ".dryft"


def _config_path(cwd: str) -> Path:
    return Path(cwd) / DRYFT_DIR / CONFIG_FILENAME


def ensure_dryft_dir(cwd: str) -> str:
    dir_path = Path(cwd) / DRYFT_DIR
    dir_path.mkdir(parents=True, exist_ok=True)
    return str(dir_path)


def load_config(cwd: str) -> dict | None:
    path = _config_path(cwd)
    try:
        raw = path.read_text(encoding="utf-8")
        data = json.loads(raw)
        if not data or not isinstance(data, dict):
            return None
        if not all(k in data and isinstance(data.get(k), str) for k in ("server_url", "project_id", "developer_id")):
            return None
        poll = data.get("poll_interval_ms")
        if not isinstance(poll, (int, float)) or poll <= 0:
            poll = DEFAULT_POLL_INTERVAL_MS
        return {
            "server_url": (data["server_url"] or "").rstrip("/"),
            "project_id": data["project_id"],
            "developer_id": data["developer_id"],
            "poll_interval_ms": int(poll),
        }
    except (OSError, json.JSONDecodeError):
        return None


def save_config(cwd: str, config: dict) -> None:
    ensure_dryft_dir(cwd)
    path = _config_path(cwd)
    data = {
        "server_url": config["server_url"],
        "project_id": config["project_id"],
        "developer_id": config["developer_id"],
        "poll_interval_ms": config.get("poll_interval_ms") or DEFAULT_POLL_INTERVAL_MS,
    }
    path.write_text(json.dumps(data, indent=2), encoding="utf-8")
