import { hash } from "node:crypto";
import { asRecord } from "./goal-record.ts";

// Comparing a message with how it looked on the last request, without holding
// big tool results twice. Used by the live-tail retention to notice a changed
// history.

/**
 * A message as it looked at the last request, kept to compare against the next
 * one. Short strings are kept as they are; long ones as a length and a hash, so
 * the copy stays small and big tool results are not held twice. Null means the
 * message could not be copied, and a null never matches anything.
 */
export type Snapshot = unknown;

/**
 * Who a message is, apart from its text: its role, time, custom type and tool
 * call. Empty when the message has no time, because then nothing separates it
 * from another message of the same role.
 */
export function identityOf(message: unknown): string {
	const record = asRecord(message);
	if (typeof record?.timestamp !== "number") return "";
	return [record.role, record.timestamp, record.customType, record.toolCallId].map(part => (typeof part === "string" || typeof part === "number" ? String(part) : "")).join("|");
}

/** Strings up to this long are kept as they are. Longer ones are hashed. */
const RAW_STRING_MAX = 4096;
/** Deeper than any real message. Guards against cycles. */
const MAX_DEPTH = 64;

class LongString {
	readonly length: number;
	readonly hash: string;
	constructor(length: number, hash: string) {
		this.length = length;
		this.hash = hash;
	}
}

const hashText = (text: string): string => hash("sha256", text, "base64");

function isPlainObject(value: object): boolean {
	const proto = Object.getPrototypeOf(value);
	return proto === Object.prototype || proto === null;
}

function copyForComparison(value: unknown, depth: number): Snapshot {
	if (typeof value === "string") return value.length > RAW_STRING_MAX ? new LongString(value.length, hashText(value)) : value;
	if (value === null || value === undefined || typeof value === "number" || typeof value === "boolean") return value;
	if (depth >= MAX_DEPTH || typeof value !== "object") throw new Error("not copyable");
	if (Array.isArray(value)) return value.map(item => copyForComparison(item, depth + 1));
	if (!isPlainObject(value)) throw new Error("not copyable");
	const copy: Record<string, Snapshot> = {};
	for (const key of Object.keys(value)) copy[key] = copyForComparison((value as Record<string, unknown>)[key], depth + 1);
	return copy;
}

/** What a message looks like once serialized, or null when it cannot be serialized. */
function serialize(message: unknown): string | null {
	try {
		return JSON.stringify(message) ?? null;
	} catch {
		return null;
	}
}

/**
 * A message the plain copy cannot hold (a class instance, a Date, a Map) is
 * compared by the hash of its JSON instead. A message that matched nothing would
 * make every request look like a rewrite and reset the retained blocks each time.
 */
class SerializedMessage {
	readonly hash: string;
	constructor(hash: string) {
		this.hash = hash;
	}
}

export function snapshotMessage(message: unknown): Snapshot | null {
	try {
		return copyForComparison(message, 0);
	} catch {
		const text = serialize(message);
		return text === null ? null : new SerializedMessage(hashText(text));
	}
}

function sameAsSnapshot(snapshot: Snapshot, value: unknown, depth = 0): boolean {
	if (snapshot instanceof SerializedMessage) {
		const text = serialize(value);
		return text !== null && hashText(text) === snapshot.hash;
	}
	if (typeof snapshot === "string") return snapshot === value;
	if (snapshot instanceof LongString) return typeof value === "string" && value.length === snapshot.length && hashText(value) === snapshot.hash;
	if (snapshot === null || typeof snapshot !== "object") return Object.is(snapshot, value);
	if (depth >= MAX_DEPTH || typeof value !== "object" || value === null) return false;
	if (Array.isArray(snapshot)) {
		if (!Array.isArray(value) || value.length !== snapshot.length) return false;
		for (let i = 0; i < snapshot.length; i++) if (!sameAsSnapshot(snapshot[i], value[i], depth + 1)) return false;
		return true;
	}
	if (Array.isArray(value) || !isPlainObject(value)) return false;
	const keys = Object.keys(snapshot);
	if (Object.keys(value).length !== keys.length) return false;
	for (const key of keys) {
		if (!Object.hasOwn(value, key) || !sameAsSnapshot((snapshot as Record<string, Snapshot>)[key], (value as Record<string, unknown>)[key], depth + 1)) return false;
	}
	return true;
}

/** True when the message is unchanged since the snapshot was taken. */
export const unchanged = (snapshot: Snapshot | null, message: unknown): boolean => snapshot !== null && sameAsSnapshot(snapshot, message);
