"use strict";

const body = document.body;
const contractPath = body.dataset.contract;
const fields = {
  providerId: document.querySelector("#provider-id"),
  server: document.querySelector("#server"),
  credentialFile: document.querySelector("#credential-file"),
  pythonRuntime: document.querySelector("#python-runtime"),
  autoStart: document.querySelector("#auto-start"),
};
const commandElement = document.querySelector("#install-command");
const statusElement = document.querySelector("#action-status");
const credentialPath = document.querySelector("#credential-path");
const agentContract = document.querySelector("#agent-contract");
const downloadLauncher = document.querySelector("#download-launcher");
const launcherNote = document.querySelector("#launcher-note");
let contract = null;
let activeLauncher = "cmd";
let activePlatform = "windows";

function validProviderId(value) {
  return /^[A-Za-z0-9_.-]{1,64}$/u.test(value);
}

function validCredentialFile(value) {
  return /^[A-Za-z0-9_.-]{1,128}$/u.test(value);
}

function yamlString(value) {
  return JSON.stringify(String(value));
}

function yamlContents() {
  return [
    `id: ${yamlString(fields.providerId.value.trim())}`,
    `server: ${yamlString(fields.server.value.trim())}`,
    `credentialFile: ${yamlString(fields.credentialFile.value.trim())}`,
    `pythonRuntime: ${fields.pythonRuntime.value}`,
    `autoStart: ${fields.autoStart.checked ? "true" : "false"}`,
    "",
  ].join("\n");
}

function renderCommand() {
  const id = fields.providerId.value.trim();
  const server = fields.server.value.trim();
  const credentialFile = fields.credentialFile.value.trim();
  const platformUi = {
    windows: {
      credentialPath: `%USERPROFILE%\\.unidesk\\${credentialFile || "provider.token"}`,
      configRoot: "%USERPROFILE%\\.unidesk",
      eyebrow: "Windows native",
      badge: "Win7 / Win10 / Win11 · 自动准备 Python",
      pythonNote: "专属环境位于 %USERPROFILE%\\.unidesk\\runtime",
      autoTitle: "登录后自动启动",
      autoNote: "写入当前用户 HKCU Run",
      runtime: "纯 Windows 用户进程",
      lifecycle: "托盘与自动升级",
    },
    linux: {
      credentialPath: `~/.unidesk/${credentialFile || "provider.token"}`,
      configRoot: "~/.unidesk",
      eyebrow: "Linux native",
      badge: "Bash · systemd · 无 Docker / Node",
      pythonNote: "专属环境位于 ~/.unidesk/runtime/linux",
      autoTitle: "开机自动启动",
      autoNote: "注册原生 systemd system service",
      runtime: "纯 Linux headless 进程",
      lifecycle: "systemd 与自动升级",
    },
  }[activePlatform];
  credentialPath.textContent = platformUi.credentialPath;
  document.querySelector("#config-root").textContent = platformUi.configRoot;
  document.querySelector("#platform-eyebrow").textContent = platformUi.eyebrow;
  document.querySelector("#platform-badge").textContent = platformUi.badge;
  document.querySelector("#python-note").textContent = platformUi.pythonNote;
  document.querySelector("#autostart-title").textContent = platformUi.autoTitle;
  document.querySelector("#autostart-note").textContent = platformUi.autoNote;
  document.querySelector("#runtime-caption").textContent = platformUi.runtime;
  document.querySelector("#lifecycle-caption").textContent = platformUi.lifecycle;
  const startCmdUrl = new URL(
    "/win.cmd",
    location.origin,
  ).href;
  const fallbackLaunchers = {
    powershell: {
      command: `irm '${new URL("/v1/unideskcprovider/install.ps1", location.origin).href}' | iex`,
      support: "Windows 10/11 · PowerShell 5.1+ · Python 3.11+",
      downloadUrl: null,
    },
    cmd: {
      command: `certutil -urlcache -f ${startCmdUrl} "%TEMP%\\u.cmd"&&call "%TEMP%\\u.cmd"`,
      support: "同一命令兼容 Win7/10/11；优先复用私有或系统 Python，缺失时自动安装专属 3.8/3.11",
      downloadUrl: startCmdUrl,
    },
    bash: {
      command: `curl -fsSL ${new URL("/linux.sh", location.origin).href} | bash`,
      support: "Linux host · Bash + systemd · 不依赖 Docker 或 Node",
      downloadUrl: new URL("/linux.sh", location.origin).href,
    },
  };
  const launcher = contract?.platforms?.[activePlatform]?.launchers?.[activeLauncher] ?? fallbackLaunchers[activeLauncher];
  commandElement.textContent = launcher.command;
  const runtimeNotes = {
    auto: "自动：系统 → 已有专属 → 安装专属",
    system: "系统：不满足即报错，不会回退",
    private: "专属：已有即复用，否则安装",
  };
  launcherNote.textContent = `${launcher.support} · ${runtimeNotes[fields.pythonRuntime.value]}`;
  downloadLauncher.classList.toggle("hidden", !launcher.downloadUrl);
  if (launcher.downloadUrl) downloadLauncher.href = launcher.downloadUrl;
  downloadLauncher.download = activePlatform === "linux" ? "install-linux.sh" : "unideskcprovider-start.cmd";
  const valid = validProviderId(id) && validCredentialFile(credentialFile) && /^wss?:\/\//u.test(server);
  document.querySelector("#copy-command").disabled = !valid;
  document.querySelector("#download-yaml").disabled = !valid;
}

function selectPlatform(platform) {
  activePlatform = platform;
  activeLauncher = platform === "linux" ? "bash" : "cmd";
  if (platform === "linux" && fields.providerId.value.trim() === "G14-win") {
    fields.providerId.value = "D601-VM-HOST";
  } else if (platform === "windows" && fields.providerId.value.trim() === "D601-VM-HOST") {
    fields.providerId.value = "G14-win";
  }
  for (const tab of document.querySelectorAll(".platform-tab")) {
    const active = tab.dataset.platform === platform;
    tab.classList.toggle("active", active);
    tab.setAttribute("aria-selected", String(active));
  }
  for (const tab of document.querySelectorAll(".launcher-tab")) {
    const visible = platform === "linux" ? tab.dataset.launcher === "bash" : tab.dataset.launcher !== "bash";
    tab.classList.toggle("hidden", !visible);
    const active = visible && tab.dataset.launcher === activeLauncher;
    tab.classList.toggle("active", active);
    tab.setAttribute("aria-selected", String(active));
  }
  renderCommand();
}

for (const tab of document.querySelectorAll(".platform-tab")) {
  tab.addEventListener("click", () => selectPlatform(tab.dataset.platform));
}

async function copyText(value, success) {
  await navigator.clipboard.writeText(value);
  statusElement.textContent = success;
}

for (const input of Object.values(fields)) {
  input.addEventListener("input", renderCommand);
  input.addEventListener("change", renderCommand);
}

document.querySelector("#copy-command").addEventListener("click", async () => {
  try {
    await copyText(commandElement.textContent, "启动命令已复制");
  } catch {
    statusElement.textContent = "浏览器未授权剪贴板，请选择命令后复制";
  }
});

for (const tab of document.querySelectorAll(".launcher-tab")) {
  tab.addEventListener("click", () => {
    activeLauncher = tab.dataset.launcher;
    for (const current of document.querySelectorAll(".launcher-tab")) {
      const active = current === tab;
      current.classList.toggle("active", active);
      current.setAttribute("aria-selected", String(active));
    }
    renderCommand();
  });
}

document.querySelector("#download-yaml").addEventListener("click", () => {
  const blob = new Blob([yamlContents()], { type: "application/yaml;charset=utf-8" });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "provider.yaml";
  link.click();
  URL.revokeObjectURL(link.href);
  statusElement.textContent = "provider.yaml 已生成";
});

document.querySelector("#copy-endpoint").addEventListener("click", async () => {
  try {
    await copyText(new URL(contractPath, location.origin).href, "Agent JSON 端点已复制");
  } catch {
    statusElement.textContent = "浏览器未授权剪贴板";
  }
});

for (const tab of document.querySelectorAll(".mode-tab")) {
  tab.addEventListener("click", () => {
    for (const current of document.querySelectorAll(".mode-tab")) {
      const active = current === tab;
      current.classList.toggle("active", active);
      current.setAttribute("aria-selected", String(active));
    }
    for (const panel of document.querySelectorAll("[data-panel]")) {
      panel.classList.toggle("hidden", panel.dataset.panel !== tab.dataset.tab);
    }
  });
}

async function loadContract() {
  try {
    const response = await fetch(contractPath, { cache: "no-store" });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    contract = await response.json();
    agentContract.textContent = JSON.stringify(contract, null, 2);
    renderCommand();
  } catch (error) {
    agentContract.textContent = JSON.stringify({ ok: false, error: String(error) }, null, 2);
    statusElement.textContent = "安装合同读取失败";
  }
}

renderCommand();
void loadContract();
