import { BasicTool } from "zotero-plugin-toolkit";
import Addon from "./addon";
import { config } from "../package.json";

const basicTool = new BasicTool();

// @ts-expect-error - Plugin instance is not typed
if (!basicTool.getGlobal("Zotero")[config.addonInstance]) {
  _globalThis.addon = new Addon();
  defineGlobal("ztoolkit", () => {
    return _globalThis.addon.data.ztoolkit;
  });
  // @ts-expect-error - Plugin instance is not typed
  Zotero[config.addonInstance] = addon;

  // Expose API for detached window (lazy loaded)
  Object.defineProperty(addon.api, "Assistant", {
    get() {
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const { Assistant } = require("./modules/assistant");
      return Assistant;
    },
  });
  Object.defineProperty(addon.api, "DetachedWindowManager", {
    get() {
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const { DetachedWindowManager } = require("./modules/ui/windowManager");
      return DetachedWindowManager;
    },
  });
  Object.defineProperty(addon.api, "ConfigManager", {
    get() {
      const {
        exportAllData,
        importAllData,
        // eslint-disable-next-line @typescript-eslint/no-require-imports
      } = require("./modules/chat/configManager");
      return { exportAllData, importAllData };
    },
  });
  Object.defineProperty(addon.api, "debugGitCli", {
    get() {
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const { debugGitCli } = require("./modules/chat/workspace/gitCli");
      return debugGitCli;
    },
  });
}

function defineGlobal(name: Parameters<BasicTool["getGlobal"]>[0]): void;
function defineGlobal(name: string, getter: () => any): void;
function defineGlobal(name: string, getter?: () => any) {
  Object.defineProperty(_globalThis, name, {
    get() {
      return getter ? getter() : basicTool.getGlobal(name);
    },
  });
}
