"""A LangGraph checkpoint saver on the app's own database (Phase 4, 29 Oct).

Saves the graph's state at the end of every run (durability "exit", see
main.py), so a later message can resume a run that paused - the interrupt()
confirmations of Phase 5. Off unless LANGGRAPH_CHECKPOINTER=postgres.

Built on SQLAlchemy Core rather than langgraph-checkpoint-postgres, which needs
psycopg 3: the app already talks to Postgres through SQLAlchemy and psycopg2,
and this needs no new package. Each checkpoint is stored whole (channel values
included) - simpler than the official saver's per-channel blobs, and enough for
a state of ~35 small keys. Semantics follow langgraph's InMemorySaver.

Never stored: bearer_token (and anything else in REDACTED_KEYS), at any depth -
it is removed from the state values, from pending writes (the run's input is
one) and from metadata before serialisation. A resumed run must therefore be
given the caller's token again (Command(update={"bearer_token": ...})).

Kept small: the newest KEEP_PER_THREAD checkpoints of each conversation, and
conversations idle for LANGGRAPH_CHECKPOINT_TTL_DAYS are removed.
"""
from __future__ import annotations

import asyncio
import logging
import os
import random
from datetime import datetime, timedelta
from typing import Any, AsyncIterator, Iterator, Optional, Sequence

import sqlalchemy as sa
from langgraph.checkpoint.base import (
    WRITES_IDX_MAP,
    BaseCheckpointSaver,
    ChannelVersions,
    Checkpoint,
    CheckpointMetadata,
    CheckpointTuple,
    get_checkpoint_id,
    get_checkpoint_metadata,
)

logger = logging.getLogger(__name__)

REDACTED_KEYS = frozenset({"bearer_token"})
KEEP_PER_THREAD = 20
# One put in this many also clears conversations idle for the TTL.
_SWEEP_ONE_IN = 200

_meta = sa.MetaData()
checkpoints_table = sa.Table(
    "lg_checkpoints", _meta,
    sa.Column("thread_id", sa.String(255), primary_key=True),
    sa.Column("checkpoint_ns", sa.String(255), primary_key=True, server_default=""),
    sa.Column("checkpoint_id", sa.String(64), primary_key=True),
    sa.Column("parent_checkpoint_id", sa.String(64), nullable=True),
    sa.Column("checkpoint_type", sa.String(32), nullable=False),
    sa.Column("checkpoint", sa.LargeBinary, nullable=False),
    sa.Column("metadata_type", sa.String(32), nullable=False),
    sa.Column("metadata_blob", sa.LargeBinary, nullable=False),
    sa.Column("created_at", sa.DateTime, nullable=False),
)
writes_table = sa.Table(
    "lg_checkpoint_writes", _meta,
    sa.Column("thread_id", sa.String(255), primary_key=True),
    sa.Column("checkpoint_ns", sa.String(255), primary_key=True, server_default=""),
    sa.Column("checkpoint_id", sa.String(64), primary_key=True),
    sa.Column("task_id", sa.String(64), primary_key=True),
    sa.Column("idx", sa.Integer, primary_key=True),
    sa.Column("channel", sa.String(255), nullable=False),
    sa.Column("value_type", sa.String(32), nullable=False),
    sa.Column("value", sa.LargeBinary, nullable=False),
    sa.Column("task_path", sa.String(255), nullable=False, server_default=""),
)


def redact(value: Any) -> Any:
    """`value` without REDACTED_KEYS, at any depth (dicts, lists, tuples)."""
    if isinstance(value, dict):
        return {k: redact(v) for k, v in value.items() if k not in REDACTED_KEYS}
    if isinstance(value, list):
        return [redact(v) for v in value]
    if isinstance(value, tuple):
        return tuple(redact(v) for v in value)
    return value


def _ttl_days() -> int:
    try:
        return max(1, int(os.getenv("LANGGRAPH_CHECKPOINT_TTL_DAYS", "7")))
    except ValueError:
        return 7


class SqlCheckpointSaver(BaseCheckpointSaver):
    """Checkpoints in lg_checkpoints / lg_checkpoint_writes (alembic c9d0e1f2a3b4)."""

    def __init__(self, engine: sa.engine.Engine, *, keep_per_thread: int = KEEP_PER_THREAD, serde=None):
        super().__init__(serde=serde)
        self.engine = engine
        self.keep_per_thread = keep_per_thread

    # ── reading ─────────────────────────────────────────────────────────────

    def _tuple(self, conn, row) -> CheckpointTuple:
        thread_id, ns, cp_id = row.thread_id, row.checkpoint_ns, row.checkpoint_id
        w = writes_table.c
        writes = conn.execute(
            sa.select(w.task_id, w.channel, w.value_type, w.value)
            .where(w.thread_id == thread_id, w.checkpoint_ns == ns, w.checkpoint_id == cp_id)
            .order_by(w.task_id, w.idx)).all()
        return CheckpointTuple(
            config={"configurable": {"thread_id": thread_id, "checkpoint_ns": ns, "checkpoint_id": cp_id}},
            checkpoint=self.serde.loads_typed((row.checkpoint_type, row.checkpoint)),
            metadata=self.serde.loads_typed((row.metadata_type, row.metadata_blob)),
            parent_config=({"configurable": {"thread_id": thread_id, "checkpoint_ns": ns,
                                             "checkpoint_id": row.parent_checkpoint_id}}
                           if row.parent_checkpoint_id else None),
            pending_writes=[(t, ch, self.serde.loads_typed((vt, v))) for t, ch, vt, v in writes],
        )

    def get_tuple(self, config) -> Optional[CheckpointTuple]:
        c = checkpoints_table.c
        thread_id = config["configurable"]["thread_id"]
        ns = config["configurable"].get("checkpoint_ns", "")
        q = sa.select(checkpoints_table).where(c.thread_id == thread_id, c.checkpoint_ns == ns)
        cp_id = get_checkpoint_id(config)
        q = q.where(c.checkpoint_id == cp_id) if cp_id else q.order_by(c.checkpoint_id.desc()).limit(1)
        with self.engine.connect() as conn:
            row = conn.execute(q).first()
            return self._tuple(conn, row) if row else None

    def list(self, config, *, filter: Optional[dict] = None, before=None,
             limit: Optional[int] = None) -> Iterator[CheckpointTuple]:
        c = checkpoints_table.c
        q = sa.select(checkpoints_table)
        if config:
            q = q.where(c.thread_id == config["configurable"]["thread_id"])
            ns = config["configurable"].get("checkpoint_ns")
            if ns is not None:
                q = q.where(c.checkpoint_ns == ns)
            if get_checkpoint_id(config):
                q = q.where(c.checkpoint_id == get_checkpoint_id(config))
        if before and get_checkpoint_id(before):
            q = q.where(c.checkpoint_id < get_checkpoint_id(before))
        q = q.order_by(c.thread_id, c.checkpoint_ns, c.checkpoint_id.desc())
        with self.engine.connect() as conn:
            rows = conn.execute(q).all()
            out = []
            for row in rows:
                if limit is not None and len(out) >= limit:
                    break
                tup = self._tuple(conn, row)
                if filter and not all(tup.metadata.get(k) == v for k, v in filter.items()):
                    continue
                out.append(tup)
        yield from out

    # ── writing ─────────────────────────────────────────────────────────────

    def put(self, config, checkpoint: Checkpoint, metadata: CheckpointMetadata,
            new_versions: ChannelVersions):
        thread_id = config["configurable"]["thread_id"]
        ns = config["configurable"].get("checkpoint_ns", "")
        stored = {**checkpoint, "channel_values": redact(dict(checkpoint.get("channel_values") or {}))}
        cp_type, cp_blob = self.serde.dumps_typed(stored)
        md_type, md_blob = self.serde.dumps_typed(redact(get_checkpoint_metadata(config, metadata)))
        c = checkpoints_table.c
        key = (c.thread_id == thread_id, c.checkpoint_ns == ns, c.checkpoint_id == checkpoint["id"])
        with self.engine.begin() as conn:
            conn.execute(sa.delete(checkpoints_table).where(*key))
            conn.execute(sa.insert(checkpoints_table).values(
                thread_id=thread_id, checkpoint_ns=ns, checkpoint_id=checkpoint["id"],
                parent_checkpoint_id=config["configurable"].get("checkpoint_id"),
                checkpoint_type=cp_type, checkpoint=cp_blob,
                metadata_type=md_type, metadata_blob=md_blob, created_at=datetime.utcnow()))
            self._prune(conn, thread_id, ns)
            if random.randrange(_SWEEP_ONE_IN) == 0:
                self._sweep(conn)
        return {"configurable": {"thread_id": thread_id, "checkpoint_ns": ns,
                                 "checkpoint_id": checkpoint["id"]}}

    def put_writes(self, config, writes: Sequence[tuple[str, Any]], task_id: str,
                   task_path: str = "") -> None:
        thread_id = config["configurable"]["thread_id"]
        ns = config["configurable"].get("checkpoint_ns", "")
        cp_id = config["configurable"]["checkpoint_id"]
        w = writes_table.c
        with self.engine.begin() as conn:
            for idx, (channel, value) in enumerate(writes):
                if channel in REDACTED_KEYS:
                    continue
                idx = WRITES_IDX_MAP.get(channel, idx)
                key = (w.thread_id == thread_id, w.checkpoint_ns == ns, w.checkpoint_id == cp_id,
                       w.task_id == task_id, w.idx == idx)
                exists = conn.execute(sa.select(w.idx).where(*key)).first() is not None
                # As InMemorySaver: an ordinary write is kept as first written;
                # the special ones (error, interrupt, resume) are replaced.
                if exists and idx >= 0:
                    continue
                if exists:
                    conn.execute(sa.delete(writes_table).where(*key))
                v_type, v_blob = self.serde.dumps_typed(redact(value))
                conn.execute(sa.insert(writes_table).values(
                    thread_id=thread_id, checkpoint_ns=ns, checkpoint_id=cp_id, task_id=task_id,
                    idx=idx, channel=channel, value_type=v_type, value=v_blob, task_path=task_path or ""))

    def delete_thread(self, thread_id: str) -> None:
        with self.engine.begin() as conn:
            conn.execute(sa.delete(writes_table).where(writes_table.c.thread_id == thread_id))
            conn.execute(sa.delete(checkpoints_table).where(checkpoints_table.c.thread_id == thread_id))

    def _prune(self, conn, thread_id: str, ns: str) -> None:
        c = checkpoints_table.c
        old = [r[0] for r in conn.execute(
            sa.select(c.checkpoint_id).where(c.thread_id == thread_id, c.checkpoint_ns == ns)
            .order_by(c.checkpoint_id.desc()).offset(self.keep_per_thread)).all()]
        if old:
            w = writes_table.c
            conn.execute(sa.delete(writes_table).where(
                w.thread_id == thread_id, w.checkpoint_ns == ns, w.checkpoint_id.in_(old)))
            conn.execute(sa.delete(checkpoints_table).where(
                c.thread_id == thread_id, c.checkpoint_ns == ns, c.checkpoint_id.in_(old)))

    def _sweep(self, conn) -> None:
        c = checkpoints_table.c
        cutoff = datetime.utcnow() - timedelta(days=_ttl_days())
        idle = sa.select(c.thread_id).group_by(c.thread_id).having(sa.func.max(c.created_at) < cutoff)
        threads = [r[0] for r in conn.execute(idle).all()]
        if threads:
            conn.execute(sa.delete(writes_table).where(writes_table.c.thread_id.in_(threads)))
            conn.execute(sa.delete(checkpoints_table).where(c.thread_id.in_(threads)))
            logger.info("[Checkpointer] removed %d conversations idle for %d days", len(threads), _ttl_days())

    # ── async: the same, off the event loop ─────────────────────────────────

    async def aget_tuple(self, config) -> Optional[CheckpointTuple]:
        return await asyncio.to_thread(self.get_tuple, config)

    async def alist(self, config, *, filter: Optional[dict] = None, before=None,
                    limit: Optional[int] = None) -> AsyncIterator[CheckpointTuple]:
        items = await asyncio.to_thread(
            lambda: list(self.list(config, filter=filter, before=before, limit=limit)))
        for item in items:
            yield item

    async def aput(self, config, checkpoint, metadata, new_versions):
        return await asyncio.to_thread(self.put, config, checkpoint, metadata, new_versions)

    async def aput_writes(self, config, writes, task_id: str, task_path: str = "") -> None:
        await asyncio.to_thread(self.put_writes, config, writes, task_id, task_path)

    async def adelete_thread(self, thread_id: str) -> None:
        await asyncio.to_thread(self.delete_thread, thread_id)


def enabled() -> bool:
    """LANGGRAPH_CHECKPOINTER=postgres turns it on. Read once, when the graph is
    compiled at import, so a change needs a restart."""
    return os.getenv("LANGGRAPH_CHECKPOINTER", "off").strip().lower() in ("postgres", "on", "true", "1")


def from_env() -> Optional[SqlCheckpointSaver]:
    """The saver when enabled(), on its own small pooled engine for DATABASE_URL
    (the app's engine is NullPool: a new connection for every query); else None."""
    if not enabled():
        return None
    url = os.getenv("DATABASE_URL")
    if not url:
        logger.error("[Checkpointer] LANGGRAPH_CHECKPOINTER is on but DATABASE_URL is not set - off")
        return None
    engine = sa.create_engine(url, pool_size=2, max_overflow=4, pool_pre_ping=True, pool_recycle=1800)
    logger.info("[Checkpointer] on - graph state saved to lg_checkpoints")
    return SqlCheckpointSaver(engine)


def thread_config(company_id, conversation_id) -> dict:
    """The run config for a conversation: one checkpoint thread per user and
    conversation."""
    return {"configurable": {"thread_id": f"{company_id}:{conversation_id}"}}
