import type { GQLKnowledgeGraphCapacity } from "@manta-eu/client";
import { useBringDatastoreOnlineMutation, useKnowledgeGraphStateQuery } from "@manta-eu/client";
import { isPresent } from "@manta-eu/lib/present";
import { usePostHog } from "@posthog/react";
import { useQueryClient } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { deriveAvailability } from "./knowledge-graph-availability";
import { useKnowledgeGraphPollInterval } from "./KnowledgeGraphPollingProvider";
import type { KnowledgeGraphStateContextValue } from "./KnowledgeGraphStateContext";
import { KnowledgeGraphStateContext } from "./KnowledgeGraphStateContext";
import { useMantaClient } from "./MantaClientProvider";
import { invalidateGraphDerivedQueries } from "#shared/graph-derived-queries";

export type KnowledgeGraphStateProviderProps = {
  children: ReactNode;
  datastoreId?: string;
};

export function KnowledgeGraphStateProvider(props: KnowledgeGraphStateProviderProps) {
  const { children, datastoreId } = props;
  const { mantaClient } = useMantaClient();
  const queryClient = useQueryClient();
  const posthog = usePostHog();
  const pollIntervalMs = useKnowledgeGraphPollInterval();
  const reportedNotProvisionedDatastoreIds = useRef(new Set<string>());

  const [previousDataVersion, setPreviousDataVersion] = useState<string>();
  const [cachedCapacity, setCachedCapacity] = useState<GQLKnowledgeGraphCapacity>();

  const { data, isLoading, error } = useKnowledgeGraphStateQuery(
    mantaClient,
    { dataVersion: previousDataVersion },
    {
      // Keep dataVersion out of the key. It only lets the server skip the triple count, and with one cache
      // entry per version the effect below can bounce between two cached answers forever.
      queryKey: useKnowledgeGraphStateQuery.getKey(),
      refetchInterval: pollIntervalMs,
      refetchIntervalInBackground: false,
      staleTime: 0,
    },
  );

  useEffect(() => {
    const rawState = data?.knowledgeGraphState;
    if (!rawState) return;

    const isCachedResponse =
      rawState.capacity.currentTriples === null &&
      rawState.capacity.percentageFull === null &&
      rawState.capacity.remainingCapacity === null &&
      rawState.capacity.entitySummary === null &&
      rawState.exists;

    if (!isCachedResponse && (rawState.capacity.currentTriples !== null || !rawState.exists)) {
      setCachedCapacity(rawState.capacity);
    }
  }, [data?.knowledgeGraphState]);

  const enrichedKnowledgeGraphState = useMemo(() => {
    const rawState = data?.knowledgeGraphState;
    if (!rawState) return null;

    const isCachedResponse =
      rawState.capacity.currentTriples === null &&
      rawState.capacity.percentageFull === null &&
      rawState.capacity.remainingCapacity === null &&
      rawState.capacity.entitySummary === null &&
      rawState.exists;

    if (isCachedResponse && cachedCapacity) {
      return {
        ...rawState,
        capacity: {
          ...rawState.capacity,
          currentTriples: cachedCapacity.currentTriples,
          percentageFull: cachedCapacity.percentageFull,
          remainingCapacity: cachedCapacity.remainingCapacity,
          entitySummary: cachedCapacity.entitySummary,
        },
      };
    } else {
      return rawState;
    }
  }, [data?.knowledgeGraphState, cachedCapacity]);

  const knowledgeGraphAvailability = useMemo(
    () => (enrichedKnowledgeGraphState ? deriveAvailability(enrichedKnowledgeGraphState) : null),
    [enrichedKnowledgeGraphState],
  );

  useEffect(
    function reportNotProvisioned() {
      if (knowledgeGraphAvailability !== "not-provisioned") return;
      if (!datastoreId) return;
      if (reportedNotProvisionedDatastoreIds.current.has(datastoreId)) return;

      reportedNotProvisionedDatastoreIds.current.add(datastoreId);

      posthog.capture("knowledge graph not provisioned", { datastoreId });
    },
    [knowledgeGraphAvailability, datastoreId, posthog],
  );

  // Datastores the server refused to bring online (e.g. decommissioned); avoids retry-spinning them.
  const bringOnlineRefusedFor = useRef(new Set<string>());

  const bringDataStoreOnline = useBringDatastoreOnlineMutation(mantaClient, {
    onSuccess: (result) => {
      if (!result.bringDatastoreOnline.success && datastoreId) {
        bringOnlineRefusedFor.current.add(datastoreId);
      }
    },
  });

  useEffect(
    function bringOnline() {
      if (!enrichedKnowledgeGraphState?.exists || !enrichedKnowledgeGraphState?.offline) return;
      if (bringDataStoreOnline.isPending) return;
      if (datastoreId && bringOnlineRefusedFor.current.has(datastoreId)) return;

      bringDataStoreOnline.mutate({});
    },
    [
      enrichedKnowledgeGraphState?.exists,
      enrichedKnowledgeGraphState?.offline,
      bringDataStoreOnline.isPending,
      bringDataStoreOnline.mutate,
      datastoreId,
    ],
  );

  useEffect(() => {
    const currentDataVersion = data?.knowledgeGraphState?.dataVersion?.uniqueId;

    if (currentDataVersion && isPresent(previousDataVersion) && previousDataVersion !== currentDataVersion) {
      void invalidateGraphDerivedQueries(queryClient);
      console.debug("Knowledge graph dataVersion changed, invalidating the knowledge graph queries");
    }

    if (currentDataVersion && currentDataVersion !== previousDataVersion) {
      console.debug(`Updating cached dataVersion from ${previousDataVersion} to ${currentDataVersion}`);
      setPreviousDataVersion(currentDataVersion);
    }
  }, [data?.knowledgeGraphState?.dataVersion?.uniqueId, queryClient, previousDataVersion]);

  const value = useMemo<KnowledgeGraphStateContextValue>(
    () => ({
      knowledgeGraphState: enrichedKnowledgeGraphState,
      knowledgeGraphAvailability,
      isKnowledgeGraphUnavailable: isPresent(knowledgeGraphAvailability) && knowledgeGraphAvailability !== "online",
      isLoading,
      error: error as Error | null,
    }),
    [enrichedKnowledgeGraphState, knowledgeGraphAvailability, isLoading, error],
  );

  return <KnowledgeGraphStateContext.Provider value={value}>{children}</KnowledgeGraphStateContext.Provider>;
}
