import { app } from "../../scripts/app.js";

app.registerExtension({
  name: "BooruGacha.Combine",

  async beforeRegisterNodeDef(nodeType, nodeData) {
    if (nodeData.name !== "BooruGachaCombine") return;

    const origCreated = nodeType.prototype.onNodeCreated;
    nodeType.prototype.onNodeCreated = function () {
      origCreated?.apply(this, arguments);

      this._bgInputCount = 0;

      // Start with two tag inputs
      this._bgAddTagInput();
      this._bgAddTagInput();

      // "Add Input" button
      this.addWidget("button", "bg_add_input", null, () => {
        this._bgAddTagInput();
        this._bgSaveCount();
        this._bgResize();
      }).label = "\u2795 Add Input";

      // "Remove Input" button
      this.addWidget("button", "bg_rm_input", null, () => {
        this._bgRemoveLastTagInput();
      }).label = "\u2716 Remove Last";
    };

    /* ---- add / remove tag inputs ------------------------------- */
    nodeType.prototype._bgAddTagInput = function () {
      this._bgInputCount++;
      this.addInput(`tags_${this._bgInputCount}`, "STRING");
    };

    nodeType.prototype._bgRemoveLastTagInput = function () {
      // Find the last tags_N input (skip ban_list)
      for (let i = this.inputs.length - 1; i >= 0; i--) {
        if (this.inputs[i].name.startsWith("tags_")) {
          // Don't remove if it's the only one left
          const tagCount = this.inputs.filter((inp) =>
            inp.name.startsWith("tags_"),
          ).length;
          if (tagCount <= 1) return;

          this.removeInput(i);
          this._bgInputCount = Math.max(1, this._bgInputCount - 1);

          // Rename remaining tag inputs to keep sequential
          let n = 0;
          for (let j = 0; j < this.inputs.length; j++) {
            if (this.inputs[j].name.startsWith("tags_")) {
              n++;
              this.inputs[j].name = `tags_${n}`;
            }
          }
          this._bgInputCount = n;
          this._bgSaveCount();
          this._bgResize();
          return;
        }
      }
    };

    nodeType.prototype._bgSaveCount = function () {
      if (!this.properties) this.properties = {};
      this.properties.bg_input_count = this._bgInputCount;
    };

    nodeType.prototype._bgResize = function () {
      const sz = this.computeSize();
      this.size[0] = Math.max(this.size[0], sz[0]);
      this.size[1] = Math.max(this.size[1], sz[1]);
      app.canvas?.setDirty(true, true);
    };

    /* ---- restore on workflow load ------------------------------- */
    const origConfigure = nodeType.prototype.onConfigure;
    nodeType.prototype.onConfigure = function (info) {
      origConfigure?.apply(this, arguments);

      const tagInputs = (this.inputs || []).filter((inp) =>
        inp.name.startsWith("tags_"),
      );
      this._bgInputCount = tagInputs.length;

      const saved = this.properties?.bg_input_count;
      if (saved && saved > this._bgInputCount) {
        for (let i = this._bgInputCount; i < saved; i++) {
          this._bgAddTagInput();
        }
      }
    };
  },
});
