import { asRecord } from "./goal-record.ts";
import { identityOf, snapshotMessage, unchanged, type Snapshot } from "./goal-message-snapshot.ts";

/**
 * Prefix-stable retention for request-only goal-state tails.
 *
 * The context hook appends live goal state to every provider request without
 * persisting it. When the next request arrives, the completed assistant turn
 * occupies the position where the previous tail sat, so request N is no
 * longer a prefix of request N+1 and implicit prompt caches (OpenAI Responses
 * / Chat Completions, which carry no explicit marker) freeze at the first
 * injection point.
 *
 * This module makes each request a true prefix of the next: previously sent
 * tails are re-inserted verbatim at their recorded anchor (the session length
 * when they were emitted), the whole preceding history is verified unchanged
 * by digest, and only genuinely new tail content is appended. Identical
 * content across repeated requests appends nothing, so tool loops and idle
 * re-requests cost zero growth.
 *
 * Three kinds of text go through here, by how often they change:
 * - state: the goal policy (rules, objective, contract, status). A change is
 *   appended as a new block that says it supersedes the earlier ones, so the
 *   cached prefix survives pause, resume and settings changes.
 * - counters: the task list snapshot. A change appends a new snapshot.
 * - ephemeral: usage, run counts and notes that are cleared by omission
 *   (scheduling waits, stall notes, one-shot reminders). It rides at the end of
 *   each request and is never retained, so nothing stale is left in history.
 *
 * A change of scope (a different goal), any history rewrite (compaction,
 * resume, session-tree moves, filter changes, middle-message edits), an unsafe
 * insertion point, or overflow performs one documented full reset instead of
 * silently shifting the prefix or corrupting message structure.
 */

const LIVE_CONTEXT_TYPE = "pi-goal-live-context";

type LiveTailKind = "goal-state" | "goal-pointer" | "goal-counters";

/** A request-only tail message. Never persisted; the hook replays it per request. */
interface LiveMessage {
	role: "custom";
	customType: typeof LIVE_CONTEXT_TYPE;
	content: string;
	display: false;
	timestamp: 0;
}

/**
 * Upper bound on retained tails per session. Retained tails are small (policy
 * blocks and task snapshots), so the steady-state wire overhead stays near a
 * few kilobytes; exceeding the bound performs a single full reset, i.e. at
 * most one prefix break per MAX_RETAINED_LIVE_TAILS changes.
 */
export const MAX_RETAINED_LIVE_TAILS = 48;

/**
 * Upper bound on policy blocks kept in history. Each change appends a block
 * that supersedes the earlier ones; past this many, one reset removes them.
 */
export const MAX_RETAINED_POLICY_BLOCKS = 12;

/** Upper bound on one-line "restored" pointers kept in history. Each is about 50 tokens. */
export const MAX_RETAINED_POINTERS = 200;

/** Said once at the top of every policy block that follows an earlier one. */
export const POLICY_SUPERSEDED_NOTE = "[This is the current goal policy. It supersedes every earlier [PI GOAL …] block above; follow only this one.]";

/** Stands in for the saved record of a session whose saved blocks are no longer tracked (a failed save, an eviction). */
export const UNKNOWN_SAVED = "unknown";

/** Sent while a draft or a hidden reminder is in charge, so the blocks already sent stay in place. */
export const GOAL_ON_HOLD_STATE = "[PI GOAL ON HOLD]\nThe goal is on hold. Ignore every earlier [PI GOAL …] block and task list above until a new goal policy block arrives.";

/** Sent when no goal is in force, so the blocks already sent stay in place. */
export const GOAL_ENDED_STATE = "[PI GOAL ENDED]\nNo goal is active now. Ignore every earlier [PI GOAL …] block and task list above; they belong to goals that are over.";

/** Sent with every request while superseded policy blocks remain in history. */
/** Sent when a new goal has no task list, so the earlier goal's list above stops counting. */
export const TASK_LIST_NONE = "[PI TASK LIST: none for the current goal. Ignore every task list above.]";

export const POLICY_RECENCY_NOTE = "Only the latest goal policy block above applies, or the block a later [PI GOAL RESTORED] line points to; other goal policy blocks are superseded.";

/** Upper bound on concurrently tracked sessions (parent plus isolated runs). */
const MAX_TRACKED_SESSIONS = 16;
/**
 * Extra historical snapshots (the task list), excluding policy blocks. Past
 * this a full reset happens. Old snapshots are cheap cached tokens; a reset
 * re-sends the whole history since the first anchor uncached, so this is sized
 * to hold the task-list updates of a long goal.
 */
export const MAX_RETAINED_COUNTER_BYTES = 24576;

interface FreshLiveTails {
	/** Goal policy. Retained; a change is appended and supersedes earlier blocks. */
	state: string;
	/** Task list snapshot. Retained; a change appends a new snapshot. */
	counters?: string | undefined;
	/** Request-only text for this request, never retained: usage, runs, notes cleared by omission. */
	ephemeral?: string | undefined;
	/** What the goal is about (usually the goal id). A different scope starts over. */
	scope?: string | undefined;
	/**
	 * `state` stands in for a goal for now: no goal, a draft, an unfocused pool or
	 * a stale checkpoint. It has no scope of its own, and a goal that follows it
	 * needs no reset, because its policy block supersedes the rest.
	 */
	interim?: boolean | undefined;
	/** With `interim`: send nothing unless goal blocks were already sent. */
	onlyIfSent?: boolean | undefined;
}

interface RetainedTail {
	anchorIndex: number;
	/** Who the message the tail follows is (see `identityOf`), so a shifted history is noticed. */
	anchorIdentity: string | null;
	content: string;
	kind: LiveTailKind;
	/** For a full policy block: the text it came from, so a return to it can point back. */
	state?: string;
}

/** The retained blocks without the copies used for comparing, so they can be saved. */
export interface RetainedState {
	tails: Array<{ anchorIndex: number; content: string; kind: LiveTailKind; state?: string }>;
	/** Changes whenever the blocks were dropped, so the same blocks added again on other history are not taken for the old ones. */
	generation: number;
	lastFresh: { state: string; counters: string | undefined; countersState: string | undefined; scope: string | undefined };
	interim: boolean;
}

interface SessionRetention {
	tails: RetainedTail[];
	generation: number;
	lastFresh: { state: string; counters: string | undefined; countersState: string | undefined; scope: string | undefined } | undefined;
	/** The request-only text sent last, so the explicit-cache marker can skip it. */
	lastEphemeral: string | undefined;
	/** Every base message as it was at the last apply; any earlier rewrite resets. */
	baseSnapshots: Array<Snapshot | null>;
	/** Who each base message is, parallel to `baseSnapshots`. */
	baseIdentities: string[];
	/** The last block sent stood in for a goal (see `interim`). */
	interim: boolean;
}


/** More changed messages than this in one request look like a rewrite, not an added note. */
const MAX_EDITED_MESSAGES = 2;

/** A short name for a message in a restart note: its role, or its custom type. */
function messageLabel(message: unknown): string {
	const record = asRecord(message);
	const role = typeof record?.role === "string" ? record.role : "message";
	return typeof record?.customType === "string" ? `${role} ${record.customType}` : role;
}


/**
 * Tool results must stay adjacent to the call they answer, so a retained tail
 * may never be inserted directly before one. Covers the Pi session role
 * (`toolResult`), the provider wire role (`tool`, as seen by marker
 * relocation), and result-bearing content blocks in either vocabulary — the
 * call side needs no guard since inserting before a call keeps the pair
 * adjacent.
 */
function splitsToolBatch(next: unknown): boolean {
	const record = asRecord(next);
	const role = record?.role;
	if (role === "toolResult" || role === "tool") return true;
	const content = record?.content;
	if (Array.isArray(content)) {
		for (const block of content) {
			const entry = asRecord(block);
			if (!entry) continue;
			const type = typeof entry.type === "string" ? entry.type : "";
			if (type === "tool_result" || type === "toolResult") return true;
			if ("toolCallId" in entry || "toolUseId" in entry) return true;
		}
	}
	return false;
}

function makeLiveMessage(content: string): LiveMessage {
	return {
		role: "custom",
		customType: LIVE_CONTEXT_TYPE,
		content,
		display: false,
		timestamp: 0,
	};
}

export class LiveTailRetention {
	private readonly sessions = new Map<string, SessionRetention>();
	/** What was last saved with the session, by key (see goal-live-persist.ts). */
	readonly saved = new Map<string, string>();

	apply<T>(sessionKey: string, base: readonly T[], fresh: FreshLiveTails | null): { messages: Array<T | LiveMessage>; transientContents: string[]; stableLength: number } {
		if (fresh === null) {
			this.sessions.delete(sessionKey);
			return { messages: [...base], transientContents: [], stableLength: base.length };
		}
		this.requests++;
		let session = this.sessions.get(sessionKey);
		if (fresh.onlyIfSent && !session?.tails.length) return this.forget(sessionKey, base);
		// Map order is insertion order, so move a session to the end each time it is
		// used. Otherwise the busiest session is the oldest one and gets evicted first.
		if (session) { this.sessions.delete(sessionKey); this.sessions.set(sessionKey, session); }
		if (!session) this.track(sessionKey, session = { tails: [], generation: ++this.generations, lastFresh: undefined, lastEphemeral: undefined, baseSnapshots: [], baseIdentities: [], interim: false });
		const reset = (why: string) => {
			// The very first request has nothing to drop, so it is not a restart.
			if (session!.tails.length > 0 || session!.lastFresh !== undefined) this.noteReset(why);
			session!.tails = [];
			session!.generation = ++this.generations;
			session!.lastFresh = undefined;
			session!.baseSnapshots = [];
			session!.baseIdentities = [];
			session!.interim = false;
		};
		// A different goal shares nothing with the earlier blocks, so start over.
		// Not after a stand-in (no goal, a draft, a stale checkpoint): the policy
		// block of the goal that follows says it supersedes everything above.
		const scope = fresh.scope ?? session.lastFresh?.scope;
		let switchedGoal = false;
		if (session.lastFresh !== undefined) {
			// A stand-in may have told the model to ignore the task list above, so send it again.
			const afterStandIn = session.interim && !fresh.interim;
			// Another goal: its policy block says it supersedes the earlier ones, so
			// nothing is dropped. Its task list is sent again, or marked empty below.
			// This holds after a stand-in too, or the old goal's list would be the only one.
			if (session.lastFresh.scope !== scope) switchedGoal = true;
			if (afterStandIn || switchedGoal) session.lastFresh = { ...session.lastFresh, counters: undefined, countersState: undefined };
		}
		// A task list that disappears under the same policy it was sent with
		// would leave the old list in history with nothing to supersede it. Under
		// a different policy (paused, blocked) the new block takes over.
		if (session.lastFresh?.counters !== undefined && fresh.counters === undefined && session.lastFresh.countersState === fresh.state) reset("the task list was removed under the same policy");
		// Tails anchored while history was empty would linger at the head once
		// real history arrives. Reset once so fresh tails anchor at the tail.
		if (session.tails.length > 0 && session.baseSnapshots.length === 0 && base.length > 0) reset("blocks were anchored before any history existed");
		// Any rewrite earlier than the anchors — middle-message edits, filter
		// changes, checkpoint normalization — breaks the prefix even when the
		// trailing message is identical, so verify the whole preceding history.
		// Pi hands every request a fresh copy of the messages, and extensions may
		// edit them, so the check compares content with what was seen last time.
		// Comparing is much cheaper than hashing every message on every request.
		// A message whose text changed but which is still the same message (same role
		// and time, as when another extension adds a note to the newest one) leaves
		// every block where it was: the cache is lost from that message on either
		// way, and moving the blocks to the end would lose it from the block on.
		// A different message at that place means the history was rewritten.
		if (session.baseSnapshots.length > base.length) reset("the history got shorter (compaction or a branch change)");
		else {
			let edited = 0;
			for (let i = 0; i < session.baseSnapshots.length; i++) {
				if (unchanged(session.baseSnapshots[i] ?? null, base[i])) continue;
				const identity = identityOf(base[i]);
				if (identity === "" || identity !== session.baseIdentities[i] || ++edited > MAX_EDITED_MESSAGES) {
					reset(`message ${i + 1} of the history changed after it was sent (${messageLabel(base[i])})`);
					break;
				}
				session.baseSnapshots[i] = snapshotMessage(base[i]);
			}
		}
		// The verified history keeps its snapshots; only new messages are copied.
		const snapshots = session.baseSnapshots;
		const identities = session.baseIdentities;
		for (let i = snapshots.length; i < base.length; i++) { snapshots.push(snapshotMessage(base[i])); identities.push(identityOf(base[i])); }
		// An unsafe anchor invalidates the whole replay. Keeping an earlier
		// policy while re-appending fresh blocks would duplicate that policy.
		let valid = 0;
		while (valid < session.tails.length) {
			const tail = session.tails[valid]!;
			if (tail.anchorIndex > base.length) break;
			if (tail.anchorIndex > 0) {
				if (tail.anchorIdentity !== identityOf(base[tail.anchorIndex - 1])) break;
			}
			if (splitsToolBatch(base[tail.anchorIndex])) break;
			valid++;
		}
		if (valid < session.tails.length) reset("a retained block lost its place in the history");
		// Nothing was sent before, so there is nothing to retire.
		if (fresh.onlyIfSent && session.tails.length === 0) return this.forget(sessionKey, base);
		// Append only what differs from the last emitted blocks, so unchanged
		// content across repeats, tool loops, and history advances adds zero
		// blocks while keeping the prefix literal. Overflow is measured against
		// what this request actually appends: an unchanged request adds nothing
		// and must never trigger a reset.
		const counterBytes = () => session!.tails.filter(tail => tail.kind === "goal-counters").reduce((n, tail) => n + Buffer.byteLength(tail.content), 0);
		const changes = () => {
			const last = session!.lastFresh;
			return {
				policy: last === undefined || last.state !== fresh.state,
				counters: fresh.counters !== undefined && (last === undefined || last.counters !== fresh.counters),
			};
		};
		let changed = changes();
		const policyBlocks = session.tails.filter(tail => tail.kind === "goal-state").length;
		const pointers = session.tails.filter(tail => tail.kind === "goal-pointer").length;
		if (session.tails.length - pointers + Number(changed.policy) + Number(changed.counters) > MAX_RETAINED_LIVE_TAILS
			|| (changed.policy && pointers >= MAX_RETAINED_POINTERS)
			|| (changed.policy && policyBlocks >= MAX_RETAINED_POLICY_BLOCKS)
			|| (changed.counters && counterBytes() + Buffer.byteLength(fresh.counters!) > MAX_RETAINED_COUNTER_BYTES)) {
			reset("a size limit was reached");
			if (fresh.onlyIfSent) return this.forget(sessionKey, base);
			changed = changes();
		}
		const messages: Array<T | LiveMessage> = [...base];
		for (let i = session.tails.length - 1; i >= 0; i--) {
			const tail = session.tails[i]!;
			messages.splice(tail.anchorIndex, 0, makeLiveMessage(tail.content));
		}
		const anchorIdentity = identities.at(-1) ?? null;
		const append = (content: string, kind: LiveTailKind, state?: string) => {
			messages.push(makeLiveMessage(content));
			session!.tails.push({ anchorIndex: base.length, anchorIdentity, content, kind, ...(state === undefined ? {} : { state }) });
		};
		if (changed.policy) {
			// A policy that returns (pause, then resume) is not sent again: one line points
			// back to the block already in history. Repeating it would add its full size
			// every time and hit the block limit after a few cycles, which resets the prefix.
			const earlier = session.tails.find(tail => tail.kind === "goal-state" && tail.state === fresh.state);
			if (earlier) {
				// Name the block by its number and its own first line: several blocks of one goal can begin alike.
				const number = session.tails.filter(tail => tail.kind === "goal-state").indexOf(earlier) + 1;
				append(`[PI GOAL RESTORED] Goal policy block #${number} above, the one that begins "${fresh.state.split("\n", 1)[0]}", is in force again, unchanged. Follow it; the goal policy blocks after it no longer apply.`, "goal-pointer");
			}
			else append(session.tails.some(tail => tail.kind !== "goal-counters") ? `${POLICY_SUPERSEDED_NOTE}\n${fresh.state}` : fresh.state, "goal-state", fresh.state);
		}
		if (changed.counters) append(fresh.counters!, "goal-counters");
		else if (switchedGoal && session.tails.some(tail => tail.kind === "goal-counters")) append(TASK_LIST_NONE, "goal-counters");
		// Request-only text goes last and is never retained. While superseded
		// policy blocks remain in history, say once per request which one counts.
		const superseded = session.tails.filter(tail => tail.kind !== "goal-counters").length > 1;
		const ephemeral = [superseded ? POLICY_RECENCY_NOTE : "", fresh.ephemeral ?? ""].filter(Boolean).join("\n");
		const stableLength = messages.length;
		if (ephemeral) messages.push(makeLiveMessage(ephemeral));
		session.baseSnapshots = snapshots;
		session.baseIdentities = identities;
		const previous = session.lastFresh;
		session.lastFresh = fresh.counters === undefined
			? { state: fresh.state, counters: previous?.counters, countersState: previous?.countersState, scope }
			: { state: fresh.state, counters: fresh.counters, countersState: fresh.state, scope };
		session.lastEphemeral = ephemeral || undefined;
		session.interim = fresh.interim === true;
		return { messages, stableLength, transientContents: [...new Set([...session.tails.map(tail => tail.content), ...(ephemeral ? [ephemeral] : [])])] };
	}

	private track(sessionKey: string, session: SessionRetention): void {
		if (this.sessions.size >= MAX_TRACKED_SESSIONS) {
			const oldest = this.sessions.keys().next();
			// What was saved for it goes too, so a later start writes a full set after a reset.
			if (!oldest.done) { this.sessions.delete(oldest.value); if (this.saved.has(oldest.value)) this.saved.set(oldest.value, UNKNOWN_SAVED); }
		}
		this.sessions.set(sessionKey, session);
	}

	/** Whether anything is retained for the session. */
	has(sessionKey: string): boolean {
		return this.sessions.has(sessionKey);
	}

	/** What is retained, in a form that can be saved and handed back to `adopt`. */
	exportState(sessionKey: string): RetainedState | undefined {
		const session = this.sessions.get(sessionKey);
		if (!session?.lastFresh) return undefined;
		return {
			tails: session.tails.map(tail => ({ anchorIndex: tail.anchorIndex, content: tail.content, kind: tail.kind, ...(tail.state === undefined ? {} : { state: tail.state }) })),
			generation: session.generation,
			lastFresh: { ...session.lastFresh },
			interim: session.interim,
		};
	}

	/** Take saved state for history the caller has already checked against `base`. */
	adopt<T>(sessionKey: string, state: RetainedState, base: readonly T[]): void {
		const snapshots = base.map(snapshotMessage);
		const identities = base.map(identityOf);
		this.track(sessionKey, {
			generation: ++this.generations,
			tails: state.tails.map(tail => ({ ...tail, anchorIdentity: tail.anchorIndex > 0 ? identities[tail.anchorIndex - 1] ?? null : null })),
			lastFresh: { ...state.lastFresh },
			lastEphemeral: undefined,
			baseSnapshots: snapshots,
			baseIdentities: identities,
			interim: state.interim,
		});
	}

	private forget<T>(sessionKey: string, base: readonly T[]): { messages: Array<T | LiveMessage>; transientContents: string[]; stableLength: number } {
		this.sessions.delete(sessionKey);
		return { messages: [...base], transientContents: [], stableLength: base.length };
	}

	contents(sessionKey: string): string[] | undefined {
		const session = this.sessions.get(sessionKey);
		if (!session) return undefined;
		const tails = session.tails.map(tail => tail.content);
		return session.lastEphemeral === undefined ? tails : [...tails, session.lastEphemeral];
	}

	clear(sessionKey?: string): void {
		if (sessionKey === undefined) { this.sessions.clear(); this.saved.clear(); }
		else this.sessions.delete(sessionKey);
	}

	/** Forget the sessions whose key matches, and leave every other session in the process alone. */
	clearMatching(matches: (sessionKey: string) => boolean): void {
		for (const key of [...this.sessions.keys()]) if (matches(key)) this.sessions.delete(key);
		for (const key of [...this.saved.keys()]) if (matches(key)) this.saved.delete(key);
	}

	private generations = 0;
	private requests = 0;
	private restarts = 0;
	private lastRestart: { why: string; request: number } | undefined;

	private noteReset(why: string): void {
		this.restarts++;
		this.lastRestart = { why, request: this.requests };
	}

	/**
	 * One line saying whether the goal blocks were ever dropped and why, for the
	 * verbose status. Each drop moves the cached prefix, so this is the first thing
	 * to look at when the provider reports cache misses.
	 */
	restartInfo(): { count: number; last: string | undefined } {
		return { count: this.restarts, last: this.lastRestart?.why };
	}

	restartNote(): string | undefined {
		if (!this.lastRestart) return this.requests > 0 ? `Goal blocks kept in place for all ${this.requests} requests` : undefined;
		return `Goal blocks restarted ${this.restarts} time${this.restarts === 1 ? "" : "s"} in ${this.requests} requests; last on request ${this.lastRestart.request}: ${this.lastRestart.why}`;
	}
}

const SHARED = Symbol.for("pi-goal-x.liveRetention");
/** Bump when the retained state changes shape, so a reload never reads an older one. */
const SHARED_VERSION = 1;

/**
 * One retention for the whole process. Pi loads the extension again on /reload,
 * which would start with nothing and send the next request without the blocks the
 * last one carried: a full cache miss for an unchanged conversation. The history
 * check still catches any real change, so reusing the old state is safe.
 */
export function sharedLiveRetention(): LiveTailRetention {
	const holder = globalThis as unknown as Record<symbol, { version: number; retention: LiveTailRetention } | undefined>;
	let shared = holder[SHARED];
	if (!shared || shared.version !== SHARED_VERSION) holder[SHARED] = shared = { version: SHARED_VERSION, retention: new LiveTailRetention() };
	return shared.retention;
}
