import { isRecord, stringField } from "@best-agent/foundation";
import type { ThreadMetadata } from "@best-agent/protocol";
import type { PendingCompactionFollowUpMarker } from "../checkpoint-codec.js";

export const COMPACTION_FOLLOW_UP_METADATA_KEY = "pendingCompactionFollowUpOperation";

export function readPendingCompactionFollowUpOperation(
  metadata: ThreadMetadata | undefined,
): PendingCompactionFollowUpMarker | undefined {
  const value = metadata?.[COMPACTION_FOLLOW_UP_METADATA_KEY];
  if (value === "manual-compact-followup" || value === "post-compact-followup") {
    return { id: "legacy", operation: value };
  }
  if (!isRecord(value)) {
    return undefined;
  }
  const id = stringField(value, "id");
  const operation = stringField(value, "operation");
  if (
    typeof id === "string" &&
    (operation === "manual-compact-followup" || operation === "post-compact-followup")
  ) {
    return { id, operation };
  }
  return undefined;
}
