import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

/**
 * Reversible single-line codec for Cursor composite tool-call ids.
 *
 * Cursor's wire delivers tool-call ids that can be two identifiers glued with a
 * literal newline ("call-<uuid>-<n>\nfc_<uuid>_<n>"). OpenCodex forwards ids
 * verbatim, so that newline leaked into Responses-visible `call_id` values,
 * where line-oriented clients (logging, splitting, validation) break. The codec
 * encodes ids containing CR/LF into a versioned single-line form. It also
 * escapes ids already in that form's reserved namespace so encoding remains
 * injective. Both forms decode back to the exact upstream bytes before
 * anything is serialized toward Cursor. Every encoded value carries a keyed tag
 * generated by this process. Prefix and base64 shape alone are never provenance:
 * an opaque upstream id may equal any stateless encoder output.
 *
 * The process key is intentionally ephemeral. After restart, the decoder leaves
 * values from the prior process unchanged rather than guessing from attacker- or
 * provider-controlled text. This keeps provenance state constant-size instead of
 * retaining an unbounded id map.
 */

const CALL_ID_PREFIX = "ocxc1_";
/** Escape namespace for ids that already sit in a reserved namespace. */
const CALL_ID_ESCAPE_PREFIX = "ocxc1e_";
const CALL_ID_PROVENANCE_DOMAIN = "opencodex:cursor-call-id:v1\0";
const CALL_ID_PROVENANCE_SEPARATOR = ".";
const CALL_ID_PROVENANCE_TAG_BYTES = 16;
let callIdProvenanceKey: Uint8Array = randomBytes(32);

/** True when the id needs encoding to survive line-oriented consumers. */
function needsEncoding(id: string): boolean {
  return id.includes("\n") || id.includes("\r");
}

/** True when the id sits in a namespace this codec owns and must be escaped. */
function isReserved(id: string): boolean {
  return id.startsWith(CALL_ID_PREFIX) || id.startsWith(CALL_ID_ESCAPE_PREFIX);
}

function provenanceTag(prefix: string, payload: string): Buffer {
  return createHmac("sha256", callIdProvenanceKey)
    .update(CALL_ID_PROVENANCE_DOMAIN)
    .update(prefix)
    .update(payload)
    .digest()
    .subarray(0, CALL_ID_PROVENANCE_TAG_BYTES);
}

function encodeWithProvenance(prefix: string, id: string): string {
  const payload = Buffer.from(id, "utf8").toString("base64url");
  const tag = provenanceTag(prefix, payload).toString("base64url");
  return `${prefix}${payload}${CALL_ID_PROVENANCE_SEPARATOR}${tag}`;
}

function hasValidProvenance(prefix: string, payload: string, tag: string): boolean {
  let received: Buffer;
  try {
    received = Buffer.from(tag, "base64url");
  } catch {
    return false;
  }
  if (
    received.byteLength !== CALL_ID_PROVENANCE_TAG_BYTES
    || received.toString("base64url") !== tag
  ) return false;
  return timingSafeEqual(received, provenanceTag(prefix, payload));
}

/** Encode a Cursor wire call id into a single-line Responses-safe id. */
export function encodeCursorCallId(id: string): string {
  // CR/LF content is the codec's actual job, so it wins the primary namespace.
  if (needsEncoding(id)) return encodeWithProvenance(CALL_ID_PREFIX, id);
  // A reserved id carries no newline; it only needs to stop looking like our output.
  if (isReserved(id)) return encodeWithProvenance(CALL_ID_ESCAPE_PREFIX, id);
  return id;
}

/**
 * Decode a Responses-visible call id back to the exact Cursor wire id.
 * Non-encoded ids (including legacy raw multi-line ids replayed by older
 * clients) pass through unchanged; a malformed encoded payload also passes
 * through rather than corrupting pairing.
 */
export function decodeCursorCallId(id: string): string {
  const escaped = id.startsWith(CALL_ID_ESCAPE_PREFIX);
  if (!escaped && !id.startsWith(CALL_ID_PREFIX)) return id;
  const prefix = escaped ? CALL_ID_ESCAPE_PREFIX : CALL_ID_PREFIX;
  const encoded = id.slice(prefix.length);
  const separator = encoded.indexOf(CALL_ID_PROVENANCE_SEPARATOR);
  if (separator <= 0 || separator !== encoded.lastIndexOf(CALL_ID_PROVENANCE_SEPARATOR)) return id;
  const payload = encoded.slice(0, separator);
  const tag = encoded.slice(separator + CALL_ID_PROVENANCE_SEPARATOR.length);
  if (!hasValidProvenance(prefix, payload, tag)) return id;
  try {
    const decoded = Buffer.from(payload, "base64url").toString("utf8");
    // Round-trip guard: only trust payloads our encoder could have produced.
    if (Buffer.from(decoded, "utf8").toString("base64url") !== payload) return id;
    // Each namespace admits exactly what its encoder puts there. An `ocxc1_` payload
    // that decodes to newline-free text is NOT our output — it is an opaque upstream
    // id that merely looks like ours, and unwrapping it would change the id.
    if (escaped ? !isReserved(decoded) : !needsEncoding(decoded)) return id;
    return decoded;
  } catch {
    return id;
  }
}

/** Simulates process restart without reloading the module. */
export function resetCursorCallIdProvenanceForTests(): void {
  callIdProvenanceKey = randomBytes(32);
}
