var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
import Buffer2 from "buffer";
import processBrowser from "process/browser";
import console from "console-browserify";
var buffer = {
  Buffer: Buffer2
};
import { activeTabId } from "../extension/utils";
import { currentWindowId } from "../extension/utils";
import * as Z from "zustand";
import { allScriptsFromDump, generateAnimationScripts } from "./replay-scripts";
const { create } = Z;
const useBlackboardPreference = create((set) => ({
  markerVisible: true,
  elementsVisible: true,
  setMarkerVisible: (visible) => {
    set({ markerVisible: visible });
  },
  setTextsVisible: (visible) => {
    set({ elementsVisible: visible });
  }
}));
const CONFIG_KEY = "midscene-env-config";
const SERVICE_MODE_KEY = "midscene-service-mode";
const HISTORY_KEY = "midscene-prompt-history";
const getConfigStringFromLocalStorage = () => {
  const configString = localStorage.getItem(CONFIG_KEY);
  return configString || "";
};
const getHistoryFromLocalStorage = () => {
  const historyString = localStorage.getItem(HISTORY_KEY);
  return historyString ? JSON.parse(historyString) : [];
};
const parseConfig = (configString) => {
  const lines = configString.split("\n");
  const config = {};
  lines.forEach((line) => {
    const trimmed = line.trim();
    if (trimmed.startsWith("#"))
      return;
    const cleanLine = trimmed.replace(/^export\s+/i, "").replace(/;$/, "").trim();
    const match = cleanLine.match(/^(\w+)=(.*)$/);
    if (match) {
      const [, key, value] = match;
      let parsedValue = value.trim();
      if (parsedValue.startsWith("'") && parsedValue.endsWith("'") || parsedValue.startsWith('"') && parsedValue.endsWith('"')) {
        parsedValue = parsedValue.slice(1, -1);
      }
      config[key] = parsedValue;
    }
  });
  return config;
};
const useChromeTabInfo = create((set) => {
  const data = {
    tabId: null,
    windowId: null
  };
  Promise.resolve().then(() => __async(void 0, null, function* () {
    const tabId = yield activeTabId();
    const windowId = yield currentWindowId();
    set({ tabId, windowId });
    chrome.tabs.onActivated.addListener((activeInfo) => __async(void 0, null, function* () {
      const tabId2 = activeInfo.tabId;
      const windowId2 = yield currentWindowId();
      set({ tabId: tabId2, windowId: windowId2 });
    }));
  }));
  return data;
});
const useEnvConfig = create((set, get) => {
  const configString = getConfigStringFromLocalStorage();
  const config = parseConfig(configString);
  const ifInExtension = window.location.href.startsWith("chrome-extension");
  const savedServiceMode = localStorage.getItem(
    SERVICE_MODE_KEY
  );
  return {
    serviceMode: ifInExtension ? "In-Browser-Extension" : savedServiceMode || "Server",
    setServiceMode: (serviceMode) => {
      if (ifInExtension)
        throw new Error("serviceMode cannot be set in extension");
      set({ serviceMode });
      localStorage.setItem(SERVICE_MODE_KEY, serviceMode);
    },
    config,
    configString,
    setConfig: (config2) => set({ config: config2 }),
    loadConfig: (configString2) => {
      const config2 = parseConfig(configString2);
      set({ config: config2, configString: configString2 });
      localStorage.setItem(CONFIG_KEY, configString2);
    },
    history: getHistoryFromLocalStorage(),
    clearHistory: () => {
      set({ history: [] });
      localStorage.removeItem(HISTORY_KEY);
    },
    addHistory: (history) => {
      const newHistory = [
        history,
        ...get().history.filter((h) => h.prompt !== history.prompt)
      ];
      while (newHistory.length > 10) {
        newHistory.pop();
      }
      set({ history: newHistory });
      localStorage.setItem(HISTORY_KEY, JSON.stringify(newHistory));
    }
  };
});
const useExecutionDump = create((set, get) => {
  let _executionDumpLoadId = 0;
  const initData = {
    dump: null,
    replayAllMode: false,
    startReplay: false,
    allExecutionAnimation: null,
    sdkVersion: null,
    modelName: null,
    insightWidth: null,
    insightHeight: null,
    activeTask: null,
    activeExecution: null,
    activeExecutionAnimation: null,
    insightDump: null,
    _insightDumpLoadId: 0,
    hoverTask: null,
    hoverTimestamp: null,
    hoverPreviewConfig: null,
    onActiveTaskChange: null
  };
  const resetActiveExecution = () => {
    set({
      activeTask: null,
      activeExecution: null,
      activeExecutionAnimation: null,
      _executionDumpLoadId: ++_executionDumpLoadId,
      insightDump: null
    });
  };
  return __spreadProps(__spreadValues({}, initData), {
    _executionDumpLoadId,
    setOnActiveTaskChange: (callback) => set({ onActiveTaskChange: callback }),
    setReplayAllMode: (replayAllMode) => {
      const state = get();
      if (state.allExecutionAnimation) {
        set({ replayAllMode });
        if (replayAllMode) {
          resetActiveExecution();
        }
      } else {
        console.error(
          "allExecutionAnimation not found, failed to set replayAllMode"
        );
      }
    },
    setStartReplay: (startReplay) => {
      set({ startReplay });
    },
    setGroupedDump: (dump) => {
      console.log("will set ExecutionDump", dump);
      set(__spreadProps(__spreadValues({}, initData), {
        dump
      }));
      if (dump && dump.executions.length > 0) {
        const setDefaultActiveTask = () => {
          if (dump && dump.executions.length > 0 && dump.executions[0].tasks.length > 0) {
            get().setActiveTask(dump.executions[0].tasks[0]);
          }
        };
        const allScriptsInfo = allScriptsFromDump(dump);
        if (!allScriptsInfo) {
          return setDefaultActiveTask();
        }
        const {
          scripts: allScripts,
          width,
          height,
          modelName,
          sdkVersion
        } = allScriptsInfo;
        console.log("allScripts", allScripts);
        set({
          allExecutionAnimation: allScripts,
          _executionDumpLoadId: ++_executionDumpLoadId,
          replayAllMode: true,
          insightWidth: width,
          insightHeight: height,
          modelName,
          sdkVersion
        });
        set({ replayAllMode: true });
      }
    },
    setActiveTask(task) {
      var _a, _b, _c;
      let parentExecution;
      let taskIndex = -1;
      const state = get();
      const dump = state.dump;
      if (dump) {
        parentExecution = dump.executions.find((execution) => {
          taskIndex = execution.tasks.indexOf(task);
          return execution.tasks.includes(task);
        });
      }
      if (!parentExecution) {
        throw new Error("parentExecution not found");
      }
      (_b = (_a = get()).onActiveTaskChange) == null ? void 0 : _b.call(_a, taskIndex, task);
      const width = state.insightWidth;
      const height = state.insightHeight;
      set({
        replayAllMode: false,
        activeTask: task,
        activeExecution: parentExecution,
        _executionDumpLoadId: ++_executionDumpLoadId,
        activeExecutionAnimation: width && height ? generateAnimationScripts(parentExecution, task, width, height) : null
      });
      console.log("will set task", task);
      if (task.type === "Insight") {
        const dump2 = (_c = task.log) == null ? void 0 : _c.dump;
        set({
          insightDump: dump2,
          _insightDumpLoadId: ++state._insightDumpLoadId
        });
      } else {
        set({ insightDump: null });
      }
    },
    setHoverTask(task, timestamp) {
      set({ hoverTask: task, hoverTimestamp: timestamp || null });
    },
    setHoverPreviewConfig(config) {
      if (config) {
        set({
          hoverPreviewConfig: {
            x: Math.floor(config.x),
            y: Math.floor(config.y)
          }
        });
      } else {
        set({ hoverPreviewConfig: null });
      }
    },
    reset: () => {
      set(initData);
    }
  });
});
const useAllCurrentTasks = () => {
  const groupedDump = useExecutionDump((store) => store.dump);
  if (!groupedDump)
    return [];
  const tasksInside = groupedDump.executions.reduce(
    (acc2, execution) => acc2.concat(execution.tasks),
    []
  );
  return tasksInside;
};
export {
  useAllCurrentTasks,
  useBlackboardPreference,
  useChromeTabInfo,
  useEnvConfig,
  useExecutionDump
};
