# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Session Checkpoint — minimal viable continuity across agent sessions.

P2-4: Save/load checkpoint so agents can resume context after a session ends.

Files live in state/session_buffer/checkpoint_{agent}_{date}.json
"""

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

_ROOT = Path(__file__).resolve().parent.parent.parent.parent
_BUFFER_DIR = _ROOT / "state" / "session_buffer"


def save_checkpoint(
    agent: str,
    task: str,
    progress: str,
    findings: list,
    files_touched: list,
) -> Path:
    """Write a session checkpoint to state/session_buffer/.

    Args:
        agent:        Agent identifier (e.g. "claude", "gemini").
        task:         Current task title or description.
        progress:     Free-text progress summary ("50% done", "blocked on X").
        findings:     List of key findings / learnings so far.
        files_touched: List of file paths modified this session.

    Returns:
        Path to the written checkpoint file.
    """
    _BUFFER_DIR.mkdir(parents=True, exist_ok=True)
    date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    path = _BUFFER_DIR / f"checkpoint_{agent}_{date_str}.json"

    payload = {
        "agent": agent,
        "task": task,
        "progress": progress,
        "findings": findings[:20],
        "files_touched": files_touched[:30],
        "timestamp": datetime.now(timezone.utc).isoformat(),
    }
    path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    return path


def load_latest_checkpoint(agent: str) -> dict | None:
    """Load the most recent checkpoint for this agent.

    Returns the checkpoint dict if one exists and is < 24h old, else None.
    """
    if not _BUFFER_DIR.exists():
        return None

    pattern = f"checkpoint_{agent}_*.json"
    candidates = sorted(_BUFFER_DIR.glob(pattern), key=lambda p: p.stat().st_mtime, reverse=True)
    if not candidates:
        return None

    latest = candidates[0]
    try:
        data = json.loads(latest.read_text(encoding="utf-8"))
    except Exception:
        return None

    # Only return if < 24 hours old
    ts_str = data.get("timestamp", "")
    if ts_str:
        try:
            saved = datetime.fromisoformat(ts_str)
            if saved.tzinfo is None:
                saved = saved.replace(tzinfo=timezone.utc)
            age_h = (datetime.now(timezone.utc) - saved).total_seconds() / 3600
            if age_h >= 24:
                return None
        except (ValueError, TypeError):
            pass

    return data
