import { spawnSync } from 'node:child_process';
import { inspect } from 'node:util';

// src/platform/ai-services/internal/force-update-policy.ts
function stringifyUnknown(value) {
  if (value === void 0 || value === null) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Buffer.isBuffer(value)) {
    return value.toString("utf8");
  }
  if (value instanceof Error) {
    return value.stack || value.message;
  }
  return inspect(value, { depth: 6, breakLength: 120 });
}
function getErrorSummary(error) {
  if (error instanceof Error) {
    return `${error.name}: ${error.message}`;
  }
  return stringifyUnknown(error) || "Unknown error";
}

// src/platform/types/app.ts
var AI_SERVICE = {
  CLAUDE: "claude",
  CODEX: "codex",
  GEMINI: "gemini"
};

// src/platform/ai-services/internal/semver.ts
var SEMVER_PATTERN = /(\d+\.\d+\.\d+)/;
function extractSemver(value) {
  const match = value.match(SEMVER_PATTERN);
  return match?.[1] ?? null;
}
var SERVICE_INSTALL_PACKAGES = {
  [AI_SERVICE.CODEX]: "@openai/codex",
  [AI_SERVICE.GEMINI]: "@google/gemini-cli",
  [AI_SERVICE.CLAUDE]: "@anthropic-ai/claude-code"
};
function getInstallPackageName(service) {
  return SERVICE_INSTALL_PACKAGES[service];
}

// src/platform/ai-services/internal/force-update-policy.ts
var FORCE_UPDATE_METADATA_PATH = "juHongE.forceUpdate";
function getPackageForceUpdatePolicy(packageName, trace) {
  trace("cli-force-update:start", `${packageName} -> ${FORCE_UPDATE_METADATA_PATH}`);
  const result = spawnSync("npm", ["view", packageName, FORCE_UPDATE_METADATA_PATH, "--json"], {
    encoding: "utf8",
    maxBuffer: 1024 * 1024,
    timeout: 15e3
  });
  if (result.error || result.status !== 0) {
    trace("cli-force-update:failed", getErrorSummary(result.error || result.stderr || result.status));
    return null;
  }
  const rawOutput = (result.stdout || "").trim();
  if (!rawOutput || rawOutput === "undefined" || rawOutput === "null") {
    trace("cli-force-update:empty", packageName);
    return null;
  }
  const parsedPolicy = parseForceUpdatePolicy(rawOutput);
  if (!parsedPolicy) {
    trace("cli-force-update:parse-failed", rawOutput);
    return null;
  }
  if (parsedPolicy.enabled && !parsedPolicy.minimumVersion) {
    trace("cli-force-update:missing-target", rawOutput);
    return {
      enabled: false
    };
  }
  trace(
    "cli-force-update:ok",
    JSON.stringify({
      enabled: parsedPolicy.enabled,
      minimumVersion: parsedPolicy.minimumVersion || ""
    })
  );
  return parsedPolicy;
}
function getForceUpdatePolicy(service, trace) {
  const packageName = getInstallPackageName(service);
  return getPackageForceUpdatePolicy(packageName, trace);
}
function parseForceUpdatePolicy(rawOutput) {
  try {
    const parsed = JSON.parse(rawOutput);
    return normalizeForceUpdatePolicy(parsed);
  } catch {
    const minimumVersion = normalizeVersionValue(rawOutput);
    if (!minimumVersion) {
      return null;
    }
    return {
      enabled: true,
      minimumVersion
    };
  }
}
function normalizeForceUpdatePolicy(value) {
  if (typeof value === "boolean") {
    return {
      enabled: value
    };
  }
  if (typeof value === "string") {
    const minimumVersion2 = normalizeVersionValue(value);
    if (!minimumVersion2) {
      return null;
    }
    return {
      enabled: true,
      minimumVersion: minimumVersion2
    };
  }
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return null;
  }
  const record = value;
  const enabled = normalizeBooleanValue(record.enabled ?? record.required ?? record.forceUpdate) ?? false;
  const minimumVersion = normalizeVersionValue(record.minimumVersion ?? record.targetVersion ?? record.version);
  return {
    enabled,
    ...minimumVersion ? { minimumVersion } : {}
  };
}
function normalizeBooleanValue(value) {
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value !== "string") {
    return void 0;
  }
  const normalized = value.trim().toLowerCase();
  if (normalized === "true") {
    return true;
  }
  if (normalized === "false") {
    return false;
  }
  return void 0;
}
function normalizeVersionValue(value) {
  if (typeof value !== "string") {
    return void 0;
  }
  return extractSemver(value.trim()) ?? void 0;
}

export { getForceUpdatePolicy, getPackageForceUpdatePolicy };
