import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
import { inheritedSessionIds, sessionReplacedAt } from "../../shared/session-succession.ts";

/** The sessions whose runs sessionId owns: itself and the sessions this process replaced on the way to it. */
export function ownerSessionIds(sessionId: string): ReadonlySet<string | undefined> {
	return new Set<string | undefined>([sessionId, ...inheritedSessionIds(sessionId)]);
}

export function ownsRun(currentSessionId: string | null | undefined, runSessionId: string | undefined): boolean {
	return currentSessionId ? ownerSessionIds(currentSessionId).has(runSessionId) : false;
}

/**
 * Like ownsRun, but a replaced session's run started after this process replaced it is not inherited:
 * another Pi process has that session open again and launched it. A run launched in this process
 * was launched before the switch, even when its runner recorded a later start.
 */
export function ownsRunStartedBeforeReplacement(
	currentSessionId: string | null | undefined,
	run: { sessionId?: string; startedAt?: number; completionOwnerId?: string } | null | undefined,
): boolean {
	if (!run || !ownsRun(currentSessionId, run.sessionId)) return false;
	if (run.sessionId === currentSessionId || run.completionOwnerId === currentCompletionOwnerId()) return true;
	const replacedAt = run.sessionId === undefined ? undefined : sessionReplacedAt(run.sessionId);
	return typeof run.startedAt !== "number" || replacedAt === undefined || run.startedAt <= replacedAt;
}
