import { reactive, ref } from "vue";
import { apiRequest } from "../api";
import { useSessions } from "./useSessions";
import { useUI } from "./useUI";

const scriptList = ref([]);
const scriptLoading = ref(false);
const scriptSaving = ref(false);
const scriptError = ref("");
const scriptSelected = ref("");
const scriptForm = reactive({ name: "", content: "" });

async function loadScripts() {
  scriptError.value = "";
  scriptLoading.value = true;
  try {
    const res = await apiRequest("/scripts", { method: "GET" });
    scriptList.value = Array.isArray(res.data) ? res.data : [];
  } catch (err) {
    scriptError.value = err.message || "加载脚本列表失败";
  } finally {
    scriptLoading.value = false;
  }
}

async function selectScript(name) {
  scriptError.value = "";
  scriptSelected.value = name;
  try {
    const res = await apiRequest(`/scripts/${encodeURIComponent(name)}`, { method: "GET" });
    scriptForm.name = res.data?.name || name;
    scriptForm.content = res.data?.content || "";
  } catch (err) {
    scriptError.value = err.message || "加载脚本内容失败";
  }
}

function resetScriptForm() {
  scriptSelected.value = "";
  scriptForm.name = "";
  scriptForm.content = "";
}

async function saveScript() {
  scriptError.value = "";
  if (!scriptSelected.value && !scriptForm.name) {
    scriptError.value = "新建脚本时 name 为必填项";
    return;
  }
  scriptSaving.value = true;
  try {
    if (scriptSelected.value) {
      await apiRequest(`/scripts/${encodeURIComponent(scriptSelected.value)}`, {
        method: "PUT", body: JSON.stringify({ content: scriptForm.content || "" }),
      });
    } else {
      await apiRequest("/scripts", {
        method: "POST",
        body: JSON.stringify({ name: scriptForm.name, content: scriptForm.content || "" }),
      });
      scriptSelected.value = scriptForm.name;
    }
    await loadScripts();
  } catch (err) {
    scriptError.value = err.message || "保存脚本失败";
  } finally {
    scriptSaving.value = false;
  }
}

async function deleteScript() {
  scriptError.value = "";
  if (!scriptSelected.value) return;
  try {
    await apiRequest(`/scripts/${encodeURIComponent(scriptSelected.value)}`, { method: "DELETE" });
    await loadScripts();
    resetScriptForm();
  } catch (err) {
    scriptError.value = err.message || "删除脚本失败";
  }
}

function applyScriptToTerminal() {
  const { sessions, activeId } = useSessions();
  const { closeOverlay } = useUI();
  const session = sessions.value.find((s) => s.id === activeId.value);
  if (!session?.ws || session.ws.readyState !== WebSocket.OPEN) {
    scriptError.value = "当前没有可用终端连接";
    return;
  }
  if (!scriptForm.content) return;
  session.ws.send(JSON.stringify({ type: "input", data: `${scriptForm.content}\n` }));
  closeOverlay();
}

export function useScripts() {
  return {
    scriptList, scriptLoading, scriptSaving, scriptError, scriptSelected, scriptForm,
    loadScripts, selectScript, resetScriptForm, saveScript, deleteScript, applyScriptToTerminal,
  };
}
