"""Lean assessment state management.

Manages assessment.json — a minimal state file tracking workflow status
and connection info only. No data duplication; customer data lives in
customer/ directory files.
"""

import json
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)

STATE_FILENAME = "assessment.json"

_working_dir: Path | None = None


def set_working_dir(path: str | Path | None) -> None:
    """Set the working directory from a tool argument."""
    global _working_dir
    if path:
        _working_dir = Path(path)


def get_working_dir() -> Path:
    """Return the working directory (explicit override or cwd)."""
    return _working_dir or Path.cwd()


def _state_path() -> Path:
    return get_working_dir() / STATE_FILENAME


def load() -> dict[str, Any]:
    """Load the state file. Returns empty dict if it doesn't exist."""
    path = _state_path()
    if path.exists():
        try:
            return json.loads(path.read_text())
        except (json.JSONDecodeError, OSError):
            logger.warning("Could not read state file at %s", path)
    return {}


def save(data: dict[str, Any]) -> None:
    """Write the state file."""
    path = _state_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2, default=str))


def update(**fields: Any) -> dict[str, Any]:
    """Merge fields into the existing state and save."""
    current = load()
    current.update(fields)
    current["updated_at"] = datetime.now(timezone.utc).isoformat()
    save(current)
    return current
