import { Capacitor } from "@capacitor/core";
import { CapacitorUpdater } from "@capgo/capacitor-updater";
import { App } from "@capacitor/app";
import semver from "semver";
import { openDapp } from "@/composables/dAppView";
import { showDialog, showConfirmDialog } from "vant";

const HOST = import.meta.env.VITE_PRO_IM_PATH  + "/updates/down/";
const UPDATE_URL = HOST + "update.json";

// 检查并更新: shasum -a 256
export async function checkAndUpdate() {
  console.log("检测更新");
  // 判断是web 还是 ios
  if (Capacitor.getPlatform() === "web") {
    console.log("web 端不支持更新");
    return;
  }
  CapacitorUpdater.notifyAppReady();
  checkForUpgrade();
}

// 更新
const checkForUpgrade = async () => {
  // 1. 拉取元数据
  console.log("拉取元数据");
  const meta = await fetch(UPDATE_URL).then((r) => r.json());
  console.log("更新", meta);

  const current = await CapacitorUpdater.current();
  const { version } = await App.getInfo();
  console.log("版本:", current.bundle.version, meta.version);
  if (!current.bundle.version) {
    console.log("无新版本！");
    return;
  }
  if (
    current.bundle.version != "builtin" &&
    semver.gte(current.bundle.version, meta.version)
  ) {
    console.log("无新版本");
    return;
  }
  if (version && semver.lt(version, meta.minBinaryVersion)) {
    console.log("壳子太旧");
    showConfirmDialog({ 
      message: '检测到新版本,是否去更新？',
    }).then(() => {
      openDapp("https://nim.angeltokens.io/apk/down/app-release.apk", { }, true);
    });
    return;
  }

  try {
    console.log("下载地址：", `${HOST}v${meta.version}.zip`);
    const update = await CapacitorUpdater.download({
      url: `${HOST}v${meta.version}.zip`,
      version: meta.version,
      checksum: meta.checksum,
    });

    // 成功
    console.log("✅ 下载成功", update);

    // 通知
    if (meta.mandatory) {
      showDialog({
        title: `v ${meta.version} 已發布`,
        confirmButtonText: "立即體驗",
        message: meta.upDataDescription,
      }).then(async () => {
        await CapacitorUpdater.set(update); // 设置新版本
      });
    }else{
      await CapacitorUpdater.set(update); // 设置新版本
    }
  } catch (err) {
    console.error("❌ 下载失败", err.message || err);
  }
};
