"""Checkpointer / state management for the deep agent."""
from __future__ import annotations

import os
from pathlib import Path
import sqlite3

ROOT = Path(__file__).resolve().parent.parent

_CHECKPOINTER = None
_CHECKPOINTER_ERROR: str | None = None
_CHECKPOINTER_INITIALIZED = False


def _env_bool(name: str, default: bool = False) -> bool:
    raw = os.getenv(name, "").strip().lower()
    if not raw:
        return default
    return raw in {"1", "true", "yes", "y", "on"}


def _resolve_checkpointer_sqlite_path() -> Path:
    raw = os.getenv("AGENT_DEEP_CHECKPOINT_SQLITE_PATH", "data/agent_state/checkpoints.sqlite").strip()
    path = Path(raw) if raw else Path("data/agent_state/checkpoints.sqlite")
    if not path.is_absolute():
        path = ROOT / path
    path.parent.mkdir(parents=True, exist_ok=True)
    return path


def _build_checkpointer():
    if not _env_bool("AGENT_DEEP_STATE_ENABLED", default=True):
        return None, None

    sqlite_path = _resolve_checkpointer_sqlite_path()
    try:
        from langgraph.checkpoint.sqlite import SqliteSaver
    except Exception as exc:
        return None, f"langgraph sqlite checkpointer unavailable: {exc}"

    try:
        connection = sqlite3.connect(str(sqlite_path), check_same_thread=False)
        saver = SqliteSaver(connection)
        saver.setup()
    except Exception as exc:
        try:
            connection.close()
        except Exception:
            pass
        return None, f"sqlite checkpointer init failed ({sqlite_path}): {exc}"
    return saver, None


def _get_checkpointer():
    global _CHECKPOINTER_INITIALIZED, _CHECKPOINTER, _CHECKPOINTER_ERROR
    if _CHECKPOINTER_INITIALIZED:
        return _CHECKPOINTER, _CHECKPOINTER_ERROR
    _CHECKPOINTER, _CHECKPOINTER_ERROR = _build_checkpointer()
    _CHECKPOINTER_INITIALIZED = True
    return _CHECKPOINTER, _CHECKPOINTER_ERROR
