"use strict";
"use client";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
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 __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var replay_scripts_exports = {};
__export(replay_scripts_exports, {
  allScriptsFromDump: () => allScriptsFromDump,
  cameraStateForRect: () => cameraStateForRect,
  generateAnimationScripts: () => generateAnimationScripts,
  mergeTwoCameraState: () => mergeTwoCameraState
});
module.exports = __toCommonJS(replay_scripts_exports);
var import_buffer = __toESM(require("buffer"));
var import_browser = __toESM(require("process/browser"));
var import_console_browserify = __toESM(require("console-browserify"));
var buffer = {
  Buffer: import_buffer.default
};
var import_utils = require("../utils");
var import_ui_utils = require("@midscene/web/ui-utils");
var import_player = require("./player.css");
const stillDuration = 900;
const actionSpinningPointerDuration = 300;
const stillAfterInsightDuration = 300;
const locateDuration = 800;
const actionDuration = 1e3;
const clearInsightDuration = 200;
const cameraStateForRect = (rect, imageWidth, imageHeight) => {
  const canvasRatio = imageWidth / imageHeight;
  const rectRatio = rect.width / rect.height;
  let rectWidthOnPage;
  if (rectRatio >= canvasRatio) {
    rectWidthOnPage = rect.width;
  } else {
    rectWidthOnPage = rect.height / imageHeight * imageWidth;
  }
  const cameraPaddingRatio = rectWidthOnPage > 400 ? 0.1 : rectWidthOnPage > 50 ? 0.2 : 0.3;
  const cameraWidth = Math.min(
    imageWidth,
    rectWidthOnPage + imageWidth * cameraPaddingRatio * 2
  );
  const cameraHeight = cameraWidth * (imageHeight / imageWidth);
  let left = Math.min(
    rect.left - imageWidth * cameraPaddingRatio,
    imageWidth - cameraWidth
  );
  left = Math.max(left, 0);
  let top = Math.min(
    rect.top - imageHeight * cameraPaddingRatio,
    imageHeight - cameraHeight
  );
  top = Math.max(top, 0);
  return {
    left: Math.round(left),
    top: Math.round(top),
    width: Math.round(cameraWidth)
  };
};
const mergeTwoCameraState = (cameraState1, cameraState2) => {
  const newLeft = Math.min(cameraState1.left, cameraState2.left);
  const newTop = Math.min(cameraState1.top, cameraState2.top);
  const newRight = Math.max(
    cameraState1.left + cameraState1.width,
    cameraState2.left + cameraState2.width
  );
  const newWidth = newRight - newLeft;
  return {
    left: newLeft,
    top: newTop,
    width: newWidth
  };
};
const allScriptsFromDump = (dump) => {
  let width = 0;
  let height = 0;
  let sdkVersion = "";
  let modelName = "";
  dump.executions.forEach((execution) => {
    execution.tasks.forEach((task) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
      const insightTask = task;
      if ((_d = (_c = (_b = (_a = insightTask.log) == null ? void 0 : _a.dump) == null ? void 0 : _b.context) == null ? void 0 : _c.size) == null ? void 0 : _d.width) {
        width = (_h = (_g = (_f = (_e = insightTask.log) == null ? void 0 : _e.dump) == null ? void 0 : _f.context) == null ? void 0 : _g.size) == null ? void 0 : _h.width;
        height = (_l = (_k = (_j = (_i = insightTask.log) == null ? void 0 : _i.dump) == null ? void 0 : _j.context) == null ? void 0 : _k.size) == null ? void 0 : _l.height;
      }
      if ((_n = (_m = insightTask.log) == null ? void 0 : _m.dump) == null ? void 0 : _n.sdkVersion) {
        sdkVersion = insightTask.log.dump.sdkVersion;
      }
      if ((_p = (_o = insightTask.log) == null ? void 0 : _o.dump) == null ? void 0 : _p.model_name) {
        modelName = insightTask.log.dump.model_name;
      }
    });
  });
  if (!width || !height) {
    import_console_browserify.default.error("width or height is missing in dump file");
    return null;
  }
  const allScripts = [];
  dump.executions.forEach((execution) => {
    const scripts = generateAnimationScripts(execution, -1, width, height);
    if (scripts) {
      allScripts.push(...scripts);
    }
  });
  const allScriptsWithoutIntermediateDoneFrame = allScripts.filter(
    (script, index) => {
      if (index !== allScripts.length - 1 && script.title === "Done") {
        return false;
      }
      return true;
    }
  );
  return {
    scripts: allScriptsWithoutIntermediateDoneFrame,
    width,
    height,
    sdkVersion,
    modelName
  };
};
const generateAnimationScripts = (execution, task, imageWidth, imageHeight) => {
  if (!execution || !execution.tasks.length)
    return null;
  if (imageWidth === 0 || imageHeight === 0) {
    return null;
  }
  let tasksIncluded = [];
  if (task === -1) {
    tasksIncluded = execution.tasks;
  } else {
    const startIndex = execution.tasks.findIndex((t) => t === task);
    if (startIndex === -1) {
      import_console_browserify.default.error("task not found, cannot generate animation scripts");
      return null;
    }
    if (startIndex === execution.tasks.length - 1) {
      return null;
    }
    for (let i = startIndex; i < execution.tasks.length; i++) {
      if (i > startIndex && execution.tasks[i].type === "Planning") {
        break;
      }
      tasksIncluded.push(execution.tasks[i]);
    }
  }
  tasksIncluded = tasksIncluded.filter(
    (task2) => task2.type !== "Assertion" && task2.type !== "Query"
  );
  if (tasksIncluded.length === 0) {
    return null;
  }
  const fullPageCameraState = cameraStateForRect(
    {
      left: 0,
      top: 0,
      width: imageWidth,
      height: imageHeight
    },
    imageWidth,
    imageHeight
  );
  const pointerScript = (img, title, subTitle) => {
    return {
      type: "pointer",
      img,
      duration: 0,
      title,
      subTitle
    };
  };
  const scripts = [];
  let insightCameraState = void 0;
  let currentCameraState = fullPageCameraState;
  let insightOnTop = false;
  const taskCount = tasksIncluded.length;
  let initSubTitle = "";
  let errorStateFlag = false;
  tasksIncluded.forEach((task2, index) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
    if (errorStateFlag)
      return;
    if (task2.type === "Planning") {
      const planningTask = task2;
      if (planningTask.recorder && planningTask.recorder.length > 0) {
        scripts.push({
          type: "img",
          img: (_b = (_a = planningTask.recorder) == null ? void 0 : _a[0]) == null ? void 0 : _b.screenshot,
          camera: fullPageCameraState,
          duration: stillDuration,
          title: (0, import_ui_utils.typeStr)(task2),
          subTitle: (0, import_ui_utils.paramStr)(task2)
        });
        initSubTitle = (0, import_ui_utils.paramStr)(task2);
      }
    } else if (task2.type === "Insight") {
      const insightTask = task2;
      const resultElement = (_c = insightTask.output) == null ? void 0 : _c.element;
      const title = (0, import_ui_utils.typeStr)(task2);
      const subTitle = (0, import_ui_utils.paramStr)(task2);
      if (resultElement == null ? void 0 : resultElement.rect) {
        insightCameraState = __spreadProps(__spreadValues({}, cameraStateForRect(resultElement.rect, imageWidth, imageHeight)), {
          pointerLeft: resultElement.center[0],
          pointerTop: resultElement.center[1]
        });
      }
      if ((_d = insightTask.log) == null ? void 0 : _d.dump) {
        const insightDump = insightTask.log.dump;
        if (!((_e = insightDump == null ? void 0 : insightDump.context) == null ? void 0 : _e.screenshotBase64)) {
          throw new Error("insight dump is required");
        }
        const insightContentLength = insightDump.context.content.length;
        if (insightDump.context.screenshotBase64WithElementMarker) {
          scripts.push({
            type: "img",
            img: insightDump.context.screenshotBase64,
            duration: stillAfterInsightDuration,
            title,
            subTitle
          });
        }
        let cameraState = void 0;
        if (currentCameraState === fullPageCameraState) {
          cameraState = void 0;
        } else if (!insightCameraState) {
          cameraState = void 0;
        } else {
          cameraState = mergeTwoCameraState(
            currentCameraState,
            insightCameraState
          );
        }
        scripts.push({
          type: "insight",
          img: insightDump.context.screenshotBase64WithElementMarker || insightDump.context.screenshotBase64,
          insightDump,
          camera: cameraState,
          duration: insightContentLength > 20 ? locateDuration : locateDuration * 0.5,
          insightCameraDuration: locateDuration,
          title,
          subTitle
        });
        scripts.push({
          type: "sleep",
          duration: stillAfterInsightDuration,
          title,
          subTitle
        });
        insightOnTop = true;
      }
    } else if (task2.type === "Action" && task2.subType !== "FalsyConditionStatement") {
      const title = (0, import_ui_utils.typeStr)(task2);
      const subTitle = (0, import_ui_utils.paramStr)(task2);
      scripts.push(pointerScript(import_utils.mousePointer, title, subTitle));
      currentCameraState = insightCameraState != null ? insightCameraState : fullPageCameraState;
      scripts.push({
        type: "img",
        img: (_g = (_f = task2.recorder) == null ? void 0 : _f[0]) == null ? void 0 : _g.screenshot,
        duration: actionDuration,
        camera: task2.subType === "Sleep" ? fullPageCameraState : insightCameraState,
        title,
        subTitle
      });
      if (insightOnTop) {
        scripts.push({
          type: "clear-insight",
          duration: clearInsightDuration,
          title,
          subTitle
        });
        insightOnTop = false;
      }
      const imgStillDuration = index < taskCount - 1 ? stillDuration : 0;
      if ((_i = (_h = task2.recorder) == null ? void 0 : _h[1]) == null ? void 0 : _i.screenshot) {
        scripts.push({
          type: "spinning-pointer",
          duration: actionSpinningPointerDuration,
          title,
          subTitle
        });
        scripts.push(pointerScript(import_utils.mousePointer, title, subTitle));
        scripts.push({
          type: "img",
          img: (_k = (_j = task2.recorder) == null ? void 0 : _j[1]) == null ? void 0 : _k.screenshot,
          duration: imgStillDuration,
          title,
          subTitle
        });
      } else {
        scripts.push({
          type: "sleep",
          duration: imgStillDuration,
          title,
          subTitle
        });
      }
    }
    if (task2.status !== "finished") {
      errorStateFlag = true;
      const errorTitle = (0, import_ui_utils.typeStr)(task2);
      const errorMsg = task2.error || "unknown error";
      const errorSubTitle = errorMsg.indexOf("NOT_IMPLEMENTED_AS_DESIGNED") > 0 ? "Further actions cannot be performed in the current environment" : errorMsg;
      scripts.push({
        type: "img",
        img: task2.recorder && task2.recorder.length > 0 ? task2.recorder[task2.recorder.length - 1].screenshot : "",
        camera: fullPageCameraState,
        duration: stillDuration,
        title: errorTitle,
        subTitle: errorSubTitle
      });
      return;
    }
  });
  if (!errorStateFlag) {
    scripts.push({
      title: "Done",
      subTitle: initSubTitle,
      type: "img",
      duration: stillDuration,
      camera: fullPageCameraState
    });
  }
  return scripts;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  allScriptsFromDump,
  cameraStateForRect,
  generateAnimationScripts,
  mergeTwoCameraState
});
