import { hash } from "node:crypto";
import { identityOf } from "./goal-message-snapshot.ts";
import { POLICY_SUPERSEDED_NOTE, UNKNOWN_SAVED, type LiveTailRetention, type RetainedState } from "./goal-live-retention.ts";

/**
 * Saves the retained goal blocks with the session, so that a restart or /resume
 * sends the same prefix as the request before it. The blocks are request-only and
 * never part of the conversation, so without this a new process starts with none
 * and the cache (a local server's, or a provider's still-warm one) is missed once.
 *
 * Only changes are saved, as small custom entries that never reach the model. Each
 * new block records a hash of the history before it. On restore a block is kept only
 * if that history is unchanged, so a compaction, a branch or an edit just starts clean.
 */
const LIVE_RETENTION_ENTRY = "pi-goal-live-tails";

type Saved = RetainedState["tails"][number];
type Fresh = RetainedState["lastFresh"];

/**
 * A policy block is saved as its text and a flag for the note in front of it, a
 * counters block as its text. The last state seen is saved as short hashes of
 * texts that are already in the saved blocks, so nothing is written twice.
 */
type Op =
	| { v: 1; model: string; op: "reset" }
	| { v: 1; model: string; op: "tail"; prefixHash: string; anchorIndex: number; kind: Saved["kind"]; text: string; noted?: true }
	| { v: 1; model: string; op: "fresh"; state: string; counters?: string; countersState?: string; scope?: string; interim: boolean };

const short = (text: string): string => hash("sha256", text, "base64").slice(0, 16);

/**
 * A message counts by who it is (role and time), the way the live check treats it, so
 * a note another extension adds to it does not stop the blocks from coming back. A
 * message with no time counts by its whole content.
 */
const messageHash = (message: unknown): string => {
	try {
		const identity = identityOf(message);
		return hash("sha256", identity !== "" ? `id:${identity}` : JSON.stringify(message) ?? "", "base64");
	} catch {
		return "";
	}
};

/** Hashes of the history before each position: the item at n covers messages 0..n-1. */
function prefixHashes(base: readonly unknown[], upTo: number): string[] {
	const out = [hash("sha256", "", "base64")];
	for (let i = 0; i < upTo; i++) out.push(hash("sha256", `${out[i]}${messageHash(base[i])}`, "base64"));
	return out;
}

const sameTail = (a: Saved, b: Saved): boolean => a.anchorIndex === b.anchorIndex && a.content === b.content && a.kind === b.kind;

/** Save what changed since the last time. `append` writes one session entry. */
export function saveLiveTails(retention: LiveTailRetention, key: string, model: string, base: readonly unknown[], append: (type: string, data: unknown) => void): void {
	const now = retention.exportState(key);
	const before = retention.saved.get(key);
	// After a failed save the session may hold blocks nobody tracks, so the next save must start with a reset.
	const dirty = before === UNKNOWN_SAVED;
	const known: RetainedState | undefined = before && !dirty ? JSON.parse(before) : undefined;
	const ops: Op[] = [];
	if (!now) {
		if (known || dirty) ops.push({ v: 1, model, op: "reset" });
		retention.saved.delete(key);
	} else {
		let common = 0;
		// With nothing known, the session may still hold blocks an earlier process saved and could not restore.
		// They must not mix with these, so say so first.
		if (!known) ops.push({ v: 1, model, op: "reset" });
		if (known) while (common < known.tails.length && common < now.tails.length && sameTail(known.tails[common]!, now.tails[common]!)) common++;
		if (known && (common < known.tails.length || known.generation !== now.generation)) { ops.push({ v: 1, model, op: "reset" }); common = 0; }
		const fresh = now.tails.slice(common);
		if (fresh.length) {
			const hashes = prefixHashes(base, Math.max(...fresh.map(tail => tail.anchorIndex)));
			for (const tail of fresh) {
				const policy = tail.kind === "goal-state" && tail.state !== undefined;
				const noted = policy && tail.content !== tail.state;
				ops.push({ v: 1, model, op: "tail", prefixHash: hashes[tail.anchorIndex] ?? "", anchorIndex: tail.anchorIndex, kind: tail.kind, text: policy ? tail.state! : tail.content, ...(noted ? { noted: true as const } : {}) });
			}
		}
		const freshState = JSON.stringify([now.lastFresh, now.interim]);
		if (ops.length || freshState !== JSON.stringify([known?.lastFresh, known?.interim])) {
			const last = now.lastFresh;
			ops.push({ v: 1, model, op: "fresh", state: short(last.state), ...(last.counters === undefined ? {} : { counters: short(last.counters) }), ...(last.countersState === undefined ? {} : { countersState: short(last.countersState) }), ...(last.scope === undefined ? {} : { scope: last.scope }), interim: now.interim });
		}
	}
	try {
		for (const op of ops) append(LIVE_RETENTION_ENTRY, op);
	} catch (error) {
		// Some of the entries may be missing from the session. Forget what was saved, so the next
		// save starts with a reset and writes everything again instead of building on a gap.
		retention.saved.set(key, UNKNOWN_SAVED);
		throw error;
	}
	if (now) retention.saved.set(key, JSON.stringify(now));
}

const KINDS = new Set(["goal-state", "goal-counters", "goal-pointer"]);
const optionalText = (value: unknown): boolean => value === undefined || typeof value === "string";

/** A damaged or unknown entry is skipped, so it cannot throw or put a block in a wrong place. */
function wellFormed(op: Op): boolean {
	switch (op.op) {
		case "reset": return true;
		case "tail": return Number.isInteger(op.anchorIndex) && op.anchorIndex >= 0 && KINDS.has(op.kind) && typeof op.text === "string" && typeof op.prefixHash === "string";
		case "fresh": return typeof op.state === "string" && optionalText(op.counters) && optionalText(op.countersState) && optionalText(op.scope) && typeof op.interim === "boolean";
		default: return false;
	}
}

/** Rebuild the saved blocks from the session's entries, if the history still matches. */
export function restoreLiveTails(retention: LiveTailRetention, key: string, model: string, entries: readonly unknown[], base: readonly unknown[]): void {
	const ops = entries.flatMap(entry => {
		const record = entry as { type?: string; customType?: string; data?: Op } | null;
		const data = record?.type === "custom" && record.customType === LIVE_RETENTION_ENTRY ? record.data : undefined;
		return data && data.v === 1 && data.model === model && wellFormed(data) ? [data] : [];
	});
	if (!ops.length) return;
	let tails: Array<Saved & { prefixHash: string }> = [];
	let last: Extract<Op, { op: "fresh" }> | undefined;
	for (const op of ops) {
		if (op.op === "reset") { tails = []; last = undefined; }
		else if (op.op === "fresh") last = op;
		else tails.push({ anchorIndex: op.anchorIndex, kind: op.kind, prefixHash: op.prefixHash, content: op.kind === "goal-state" && op.noted ? `${POLICY_SUPERSEDED_NOTE}\n${op.text}` : op.text, ...(op.kind === "goal-state" ? { state: op.text } : {}) });
	}
	// The last state is named by hashes of texts the saved blocks already hold.
	const texts = new Map<string, string>();
	for (const tail of tails) texts.set(short(tail.kind === "goal-state" ? tail.state! : tail.content), tail.kind === "goal-state" ? tail.state! : tail.content);
	const lastFresh: Fresh | undefined = last && texts.has(last.state) && (last.counters === undefined || texts.has(last.counters)) && (last.countersState === undefined || texts.has(last.countersState))
		? { state: texts.get(last.state)!, counters: last.counters === undefined ? undefined : texts.get(last.counters), countersState: last.countersState === undefined ? undefined : texts.get(last.countersState), scope: last.scope }
		: undefined;
	const interim = last?.interim ?? false;
	// Only the blocks still standing have to match the history.
	if (!lastFresh || !tails.length || tails.some(tail => tail.anchorIndex > base.length)) return;
	// Blocks are always saved in the order they sit in the history; a different order means the entries were damaged.
	if (tails.some((tail, i) => i > 0 && tail.anchorIndex < tails[i - 1]!.anchorIndex)) return;
	const hashes = prefixHashes(base, Math.max(...tails.map(tail => tail.anchorIndex)));
	if (tails.some(tail => hashes[tail.anchorIndex] !== tail.prefixHash)) return;
	const state: RetainedState = { tails: tails.map(({ prefixHash: _hash, ...tail }) => tail), generation: 0, lastFresh, interim };
	retention.adopt(key, state, base);
	// Keep what is now live (with its new generation), so the next save sees no change.
	retention.saved.set(key, JSON.stringify(retention.exportState(key) ?? state));
}
