/*
  Sub-Store operator (production-friendly)
  - Pull dynamic value from current_domain.json / current_ip.json
  - Replace vmess server field for matched nodes
*/

const VALUE_JSON_URL = "https://git.dewofaurora.de/aurora/vmess-domain-rotator/raw/runtime-state/runtime/current_domain.json";
const NODE_NAME_REGEX = /(argo|cf|vm|优选)/i;
const CACHE_KEY = "vmess-domain-rotator:current";
const CACHE_TTL_MS = 5 * 60 * 1000;
const JSON_VALUE_KEYS = ["domain", "ip"];

async function fetchValueViaSubStore() {
  const $ = $substore;
  const { body, statusCode } = await $.http.get({
    url: VALUE_JSON_URL,
    headers: {
      Accept: "application/json",
      "Cache-Control": "no-cache"
    },
    timeout: 5000
  });

  if (statusCode < 200 || statusCode >= 300) {
    throw new Error(`http status ${statusCode}`);
  }

  const obj = JSON.parse(body || "{}");
  let value = "";
  for (const key of JSON_VALUE_KEYS) {
    value = String(obj[key] || "").trim().toLowerCase();
    if (value) break;
  }

  if (!value) {
    throw new Error(`empty value field, expected one of: ${JSON_VALUE_KEYS.join(", ")}`);
  }
  return value;
}

async function operator(proxies = [], targetPlatform, context) {
  const cache = scriptResourceCache;
  let value = cache.get(CACHE_KEY);

  if (!value) {
    try {
      value = await fetchValueViaSubStore();
      cache.set(CACHE_KEY, value, CACHE_TTL_MS);
    } catch (e) {
      console.log(`[vmess-domain-rotator] fetch failed: ${e.message}`);
      return proxies;
    }
  }

  let updated = 0;
  for (const p of proxies) {
    if (!p || p.type !== "vmess") continue;
    if (!NODE_NAME_REGEX.test(p.name || "")) continue;

    if (p.server !== value) {
      p.server = value;
      updated += 1;
    }
  }

  console.log(`[vmess-domain-rotator] value=${value}, updated=${updated}, total=${proxies.length}, target=${targetPlatform}`);
  return proxies;
}
