// ── Model Routing select ─────────────────────────────────────────────
// Single <select> with three <optgroup>s (SPIDER / COREWEAVE / API).
// Picking an option switches `agents.defaults.model.primary` via
// config.patch. Compact one-row presentation — no horizontal scroll,
// no vertical bloat from listing every option in the panel.

(function () {
  // <option value> → fully-qualified model id understood by the gateway
  // (provider/model split on first "/"; later slashes survive and are
  // part of the model id, e.g. for HuggingFace paths).
  const MODEL_IDS = {
    // SPIDER
    "spider-gemma4": "spider-gemma4/TrevorJS/gemma-4-31B-it-uncensored",
    "spider-qwen35": "spider-qwen35/Qwen/Qwen3.5-35B-A3B-FP8",
    "spider-qwen35-uncen":
      "spider-qwen35-uncen/Li101/Qwen3.5-35B-A3B-Uncensored-Aggressive-safetensors",
    "spider-qwen36": "spider-qwen36/Qwen/Qwen3.6-35B-A3B-FP8",
    // COREWEAVE
    coreweave1: "qwen-cw/qwen35-35b-fp8",
    coreweave2: "qwen-cw2/qwen36-35b-fp8",
    coreweave3: "qwen-cw3/qwen36-27b-fp8",
    // API
    api: "anthropic/claude-sonnet-4-6",
  };

  // Reverse: model id → option value (for setActive lookup).
  const idToValue = {};
  for (const [value, id] of Object.entries(MODEL_IDS)) {
    idToValue[id] = value;
  }

  const select = document.getElementById("model-toggle");
  const statusEl = document.getElementById("model-status");

  if (!select) {
    return;
  }

  let currentHash = null;

  function setActive(primaryId) {
    const value = idToValue[primaryId];
    if (value) {
      select.value = value;
    } else {
      // Unknown model id — leave the placeholder visible.
      select.value = "";
    }
  }

  async function init() {
    try {
      const cfg = await window.gateway.rpc("config.get", {});
      currentHash = cfg.hash || null;
      const primaryId = cfg.config?.agents?.defaults?.model?.primary || "";
      setActive(primaryId);
      window.activeModelId = primaryId;
      statusEl.textContent = "";
    } catch (err) {
      console.warn("[models] init failed:", err.message);
      statusEl.textContent = "error loading";
    }
  }

  async function switchToModelId(newId) {
    if (!newId) {
      return;
    }
    setActive(newId);
    window.activeModelId = newId;
    statusEl.textContent = "switching…";

    try {
      const freshCfg = await window.gateway.rpc("config.get", {});
      currentHash = freshCfg.hash;

      await window.gateway.rpc("config.patch", {
        baseHash: currentHash,
        raw: JSON.stringify({
          agents: { defaults: { model: { primary: newId } } },
        }),
      });

      statusEl.textContent = "applied";
      // Profile arrives via WebSocket "profile" event after reload
    } catch (err) {
      console.warn("[models] switch failed:", err.message);
      statusEl.textContent = "switch failed";
      setTimeout(init, 1500);
    }
  }

  // Listen for profile broadcasts to update status text
  window.addEventListener("symi:profile-changed", (e) => {
    const profile = e.detail;
    if (profile?.label) {
      statusEl.textContent = profile.label;
      // Clear after 3s
      setTimeout(() => {
        if (statusEl.textContent === profile.label) {
          statusEl.textContent = "";
        }
      }, 3000);
    }
  });

  select.addEventListener("change", () => {
    const id = MODEL_IDS[select.value];
    if (id) {
      void switchToModelId(id);
    }
  });

  window.addEventListener("gateway:connected", () => init());
  if (window.gateway && window.gateway.connected) {
    void init();
  }
})();
