export type RuntimeSessionContext = {
  accessToken?: string;
  actorKey: string;
  authExpired?: {
    message: string;
    reason: "access_token_expired" | "access_token_rejected";
  };
  allowLearningWrite?: boolean;
  clientSessionId: string;
  learningMode?: "interactive" | "review";
  memoryListReadScopes?: Partial<Record<"user" | "workspace", boolean>>;
  network?: string;
  projectId?: string;
  projectKey: string;
  sessionId: string;
  tokenExpiresAt?: string;
  traceId: string;
};

const contexts = new Map<string, RuntimeSessionContext>();

export const setRuntimeSessionContext = (context: RuntimeSessionContext) => {
  contexts.set(context.sessionId, { ...context });
};

export const getRuntimeSessionContext = (sessionId: string) => {
  const context = contexts.get(sessionId);
  return context ? { ...context } : null;
};

export const markRuntimeSessionAuthExpired = (
  sessionId: string,
  reason: NonNullable<RuntimeSessionContext["authExpired"]>["reason"],
  message = "登录态已过期，请刷新登录后重试",
) => {
  const context = contexts.get(sessionId);
  if (!context) {
    return null;
  }
  const nextContext: RuntimeSessionContext = {
    ...context,
    authExpired: { message, reason },
  };
  contexts.set(sessionId, nextContext);
  return { ...nextContext };
};

export const removeRuntimeSessionContext = (sessionId: string) => {
  contexts.delete(sessionId);
};
