"""Pending project refresh marker after sync/scaffold updates.

When co sync or co scaffold actually writes content, we drop a small JSON
marker under .agent/. session_init / session_gate read it and append
instructions for the AI to refresh project/ (status Quick Reference, etc.).
"""

from __future__ import annotations

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

# Single file in agent root; not part of protocol bundle — local only.
PENDING_REFRESH_FILENAME = ".cokodo_pending_refresh.json"


def _marker_path(agent_dir: Path) -> Path:
    return agent_dir / PENDING_REFRESH_FILENAME


def write_pending_refresh(
    agent_dir: Path,
    *,
    source: str,
    summary: str,
    paths: list[str] | None = None,
) -> None:
    """Write marker when sync or scaffold made real updates."""
    data: dict[str, Any] = {
        "source": source,
        "at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "summary": summary,
    }
    if paths:
        # Cap list size to keep file small
        data["paths"] = paths[:80]
        if len(paths) > 80:
            data["paths_truncated"] = True
    path = _marker_path(agent_dir)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def read_pending_refresh(agent_dir: Path) -> dict[str, Any] | None:
    """Return marker dict if present and valid; else None."""
    path = _marker_path(agent_dir)
    if not path.is_file():
        return None
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None


def clear_pending_refresh(agent_dir: Path) -> bool:
    """Remove marker file. Returns True if file existed and was removed."""
    path = _marker_path(agent_dir)
    if not path.is_file():
        return False
    try:
        path.unlink()
        return True
    except OSError:
        return False
