import { QueryClient, useQuery } from '@tanstack/react-query';
import axios, { AxiosError, isAxiosError } from 'axios';
import '@amplitude/unified';
import { useState, useEffect } from 'react';

// recce-source/js/src/lib/const.ts
var apiUrl = process.env.NEXT_PUBLIC_API_URL;
apiUrl ??= typeof window !== "undefined" ? window.location.origin : "";
var PUBLIC_API_URL = apiUrl;
process.env.NEXT_PUBLIC_CLOUD_WEB_URL;

// recce-source/js/src/lib/api/axiosClient.ts
var axiosClient = axios.create({
  baseURL: PUBLIC_API_URL
});
var reactQueryClient = new QueryClient();

// recce-source/js/src/lib/api/types.ts
function isQueryRun(run) {
  return run.type === "query";
}

// recce-source/js/src/lib/api/runs.ts
function mutateAddKey(run) {
  if (run.result == null) {
    return run;
  }
  if (isQueryRun(run)) {
    run.result.columns = run.result.columns.map((c) => {
      if (c.key) {
        return c;
      }
      c.key = c.name;
      return c;
    });
  }
  return run;
}
async function submitRun(type, params, options) {
  const track_props = options?.trackProps ? { ...options.trackProps } : {};
  const response = await axiosClient.post("/api/runs", {
    type,
    params,
    nowait: options?.nowait,
    track_props
  });
  return response.data;
}
async function getRun(runId) {
  const response = await axiosClient.get(
    `/api/runs/${runId}`
  );
  return response.data;
}
async function waitRun(runId, timeout) {
  const response = await axiosClient.get(
    `/api/runs/${runId}/wait`,
    {
      params: {
        timeout
      }
    }
  );
  return mutateAddKey(response.data);
}
async function cancelRun(runId) {
  return await axiosClient.post(
    `/api/runs/${runId}/cancel`
  );
}
async function submitRunFromCheck(checkId, options) {
  const response = await axiosClient.post(`/api/checks/${checkId}/run`, {
    nowait: options?.nowait
  });
  return response.data;
}
async function searchRuns(type, params, limit) {
  const response = await axiosClient.post(
    `/api/runs/search`,
    {
      type,
      params,
      limit
    }
  );
  return response.data;
}
async function listRuns() {
  const response = await axiosClient.get(
    "/api/runs"
  );
  return response.data;
}
async function aggregateRuns() {
  const response = await axiosClient.post(`/api/runs/aggregate`, {});
  return response.data;
}

// recce-source/js/src/lib/api/adhocQuery.ts
async function submitQuery(params, options) {
  return await submitRun("query", params, options);
}
async function submitQueryBase(params, options) {
  return await submitRun("query_base", params, options);
}
async function submitQueryDiff(params, options) {
  return await submitRun("query_diff", params, options);
}

// recce-source/js/src/lib/api/cacheKeys.ts
var cacheKeys = {
  rowCount: (model) => ["row_count", model],
  lineage: () => ["lineage"],
  checks: () => ["checks", "list"],
  check: (checkId) => ["checks", checkId],
  checkEvents: (checkId) => ["checks", checkId, "events"],
  runs: () => ["runs"],
  run: (runId) => ["runs", runId],
  runsAggregated: () => ["runs_aggregated"],
  flag: () => ["flag"],
  instanceInfo: () => ["instance_info"],
  user: () => ["user"]
};

// recce-source/js/src/lib/api/checks.ts
async function createSimpleCheck() {
  const response = await axiosClient.post("/api/checks", {
    type: "simple"
  });
  return response.data;
}
async function createCheckByRun(runId, viewOptions) {
  const track_props = {};
  const response = await axiosClient.post("/api/checks", {
    run_id: runId,
    view_options: viewOptions,
    track_props
  });
  return response.data;
}
async function listChecks() {
  return (await axiosClient.get("/api/checks")).data;
}
function useChecks(enabled) {
  return useQuery({
    queryKey: cacheKeys.checks(),
    queryFn: listChecks,
    enabled
  });
}
async function getCheck(checkId) {
  const response = await axiosClient.get(`/api/checks/${checkId}`);
  return response.data;
}
async function updateCheck(checkId, payload) {
  const response = await axiosClient.patch(`/api/checks/${checkId}`, payload);
  return response.data;
}
async function deleteCheck(checkId) {
  const response = await axiosClient.delete(`/api/checks/${checkId}`);
  return response.data;
}
async function reorderChecks(order) {
  return await axiosClient.post("/api/checks/reorder", order);
}
async function markAsPresetCheck(checkId) {
  await axiosClient.post(`/api/checks/${checkId}/mark-as-preset`);
}

// recce-source/js/src/lib/api/cll.ts
async function getCll(input) {
  const response = await axiosClient.post("/api/cll", input);
  return response.data;
}

// recce-source/js/src/lib/api/connectToCloud.ts
async function connectToCloud() {
  const data = await axiosClient.post("/api/connect");
  return data.data;
}

// recce-source/js/src/lib/api/flag.ts
async function getServerFlag() {
  return (await axiosClient.get("/api/flag")).data;
}
async function markOnboardingCompleted() {
  try {
    await axiosClient.post(
      "/api/onboarding/completed"
    );
  } catch (_error) {
  }
}
async function markRelaunchHintCompleted() {
  try {
    await axiosClient.post(
      "/api/relaunch-hint/completed"
    );
  } catch (_error) {
  }
}
async function getLineage(base = false) {
  const response = await axiosClient.get(
    `/api/lineage?base=${base}`
  );
  return response.data;
}
async function getLineageWithError(base = false) {
  try {
    const data = await getLineage(base);
    return { data };
  } catch (err) {
    if (err instanceof AxiosError) {
      const data = err.response?.data;
      const detail = data?.detail;
      if (detail) {
        return { error: detail };
      } else {
        return { error: err.message };
      }
    } else if (err instanceof Error) {
      return { error: err.message };
    } else {
      return { error: "An unknown error occurred" };
    }
  }
}
async function getLineageDiff() {
  const [base, current] = await Promise.all([
    getLineageWithError(true),
    getLineageWithError(false)
  ]);
  return {
    base: base.data,
    current: current.data,
    base_error: base.error,
    current_error: current.error
  };
}
async function getServerInfo() {
  return (await axiosClient.get(`/api/info`)).data;
}
async function getModelInfo(model) {
  return (await axiosClient.get(
    `/api/model/${model}`
  )).data;
}

// recce-source/js/src/lib/api/lineagecheck.ts
async function createLineageDiffCheck(viewOptions) {
  const response = await axiosClient.post("/api/checks", {
    type: "lineage_diff",
    params: {},
    view_options: viewOptions
  });
  return response.data;
}

// recce-source/js/src/lib/api/rowcount.ts
async function submitRowCountDiff(params, options) {
  return await submitRun("row_count_diff", params, options);
}

// recce-source/js/src/lib/api/models.ts
async function fetchModelRowCount(modelName) {
  const response = await axiosClient.get(
    `/api/models/${modelName}/row_count`
  );
  return response.data;
}
async function queryModelRowCount(modelName) {
  const { result } = await queryRowCount([modelName]);
  return result[modelName];
}
async function queryRowCount(modelNames) {
  if (modelNames.length === 0) {
    throw new Error("No model names provided");
  }
  const { run_id } = await submitRowCountDiff(
    { node_names: modelNames },
    { nowait: true }
  );
  const run = await waitRun(run_id);
  return {
    runId: run_id,
    result: run.result
  };
}

// recce-source/js/src/lib/api/profile.ts
async function submitProfileDiff(params, options) {
  return await submitRun("profile_diff", params, options);
}

// recce-source/js/src/lib/api/schemacheck.ts
async function createSchemaDiffCheck(params) {
  const response = await axiosClient.post("/api/checks", {
    type: "schema_diff",
    params
  });
  return response.data;
}

// recce-source/js/src/lib/api/select.ts
async function select(input) {
  return (await axiosClient.post(
    `/api/select`,
    input
  )).data;
}
async function saveAs(input) {
  return (await axiosClient.post(
    "/api/save-as",
    input
  )).data;
}
async function rename(input) {
  return (await axiosClient.post(
    "/api/rename",
    input
  )).data;
}
async function exportState() {
  return (await axiosClient.post("/api/export")).data;
}
async function importState(file, checksOnly) {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("checks_only", (!!checksOnly).toString());
  return (await axiosClient.post(
    "/api/import",
    formData
  )).data;
}
async function isStateSyncing() {
  const response = await axiosClient.get(
    "/api/sync"
  );
  return response.status === 208;
}
async function syncState(input) {
  try {
    const response = await axiosClient.post("/api/sync", input);
    if (response.status === 202) {
      return {
        status: "accepted"
      };
    }
    if (response.status === 208) {
      return {
        status: "syncing"
      };
    }
  } catch (error) {
    if (isAxiosError(error)) {
      if (error.response?.status === 409) {
        return { status: "conflict" };
      }
    }
  }
  throw new Error("Failed to sync state");
}
async function shareState() {
  return (await axiosClient.post(
    "/api/share"
  )).data;
}
async function fetchUser() {
  try {
    const response = await axiosClient.get(
      "/api/users"
    );
    return response.data;
  } catch (error) {
    console.error("Error fetching user data:", error);
    throw error;
  }
}
async function fetchGitHubAvatar(userId) {
  try {
    const response = await axios.get(
      `https://api.github.com/user/${userId}`
    );
    return response.data.avatar_url;
  } catch (error) {
    console.warn("Failed to fetch GitHub avatar:", error);
    return null;
  }
}

// recce-source/js/src/lib/api/valuediff.ts
async function submitValueDiff(params, options) {
  return await submitRun("value_diff", params, options);
}
async function submitValueDiffDetail(params, options) {
  return await submitRun("value_diff_detail", params, options);
}
function useVersionNumber() {
  const [version, setVersion] = useState("");
  const [latestVersion, setLatestVersion] = useState("");
  useEffect(() => {
    async function fetchVersion() {
      try {
        const { version: version2, latestVersion: latestVersion2 } = (await axiosClient.get(
          "/api/version"
        )).data;
        setVersion(version2);
        setLatestVersion(latestVersion2);
      } catch (error) {
        console.error("Error fetching version number:", error);
      }
    }
    void fetchVersion();
  }, []);
  return { version, latestVersion };
}

// recce-source/js/src/lib/api/localStorageKeys.ts
var prefix = "recce-";
var localStorageKeys = {
  bypassSaveOverwrite: `${prefix}-bypass-save-overwrite`,
  previewChangeFeedbackID: `${prefix}-preview-change-feedback`,
  prepareEnvGuideID: `${prefix}-prepare-env`
};

// recce-source/js/src/lib/api/sessionStorageKeys.ts
var prefix2 = "recce";
var sessionStorageKeys = {
  recommendationIgnored: `${prefix2}-recommendation-ignored`,
  recommendationShowed: `${prefix2}-recommendation-showed`,
  prevRefreshTimeStamp: `${prefix2}-prev-refresh-timestamp`,
  lineageNotificationDismissed: `${prefix2}-lineage-notification-dismissed`
};

export { aggregateRuns, axiosClient, cancelRun, connectToCloud, createCheckByRun, createLineageDiffCheck, createSchemaDiffCheck, createSimpleCheck, deleteCheck, exportState, fetchGitHubAvatar, fetchModelRowCount, fetchUser, getCheck, getCll, getLineage, getLineageDiff, getLineageWithError, getModelInfo, getRun, getServerFlag, getServerInfo, importState, isStateSyncing, listChecks, listRuns, localStorageKeys, markAsPresetCheck, markOnboardingCompleted, markRelaunchHintCompleted, queryModelRowCount, queryRowCount, reactQueryClient, rename, reorderChecks, saveAs, searchRuns, select, sessionStorageKeys, shareState, submitProfileDiff, submitQuery, submitQueryBase, submitQueryDiff, submitRowCountDiff, submitRun, submitRunFromCheck, submitValueDiff, submitValueDiffDetail, syncState, updateCheck, useChecks, useVersionNumber, waitRun };
//# sourceMappingURL=api.mjs.map
//# sourceMappingURL=api.mjs.map