export interface WorkbenchNavigationContext {
  componentActive: boolean;
  routeName?: unknown;
  routePath?: unknown;
  routeSection?: unknown;
  routeSessionId?: string | null;
  sessionId?: string | null;
  activeSelectionSource?: unknown;
  applyingRouteSession?: boolean;
}

const WORKBENCH_ROUTE_NAMES = new Set(["CodeWorkbench", "CodeWorkbenchSession"]);

export function isWorkbenchNavigationContext(input: WorkbenchNavigationContext): boolean {
  if (!input.componentActive) return false;
  if (input.routeSection === "workbench") return true;
  if (typeof input.routeName === "string" && WORKBENCH_ROUTE_NAMES.has(input.routeName)) return true;
  if (typeof input.routePath !== "string") return false;
  return input.routePath === "/workbench" || input.routePath === "/workspace" || input.routePath.startsWith("/workbench/") || input.routePath.startsWith("/workspace/");
}

export function shouldReflectWorkbenchConversationUrl(input: WorkbenchNavigationContext): boolean {
  return shouldReflectWorkbenchSessionUrl(input);
}

export function shouldReflectWorkbenchSessionUrl(input: WorkbenchNavigationContext): boolean {
  if (!input.sessionId) return false;
  if (!isWorkbenchNavigationContext(input)) return false;
  if (input.routeSessionId === input.sessionId) return false;
  if (input.applyingRouteSession && input.routeSessionId && input.routeSessionId !== input.sessionId && input.activeSelectionSource !== "user" && !isCanonicalRoutePair(input.routeSessionId, input.sessionId)) return false;
  return true;
}

function isCanonicalRoutePair(routeSessionId: string | null | undefined, sessionId: string | null | undefined): boolean {
  if (!routeSessionId || !sessionId) return false;
  if (!routeSessionId.startsWith("cnv_") || !sessionId.startsWith("ses_")) return false;
  return routeSessionId.slice("cnv_".length) === sessionId.slice("ses_".length);
}
