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

// src/platform/app/self-update.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/ai-services/internal/semver.ts
var SEMVER_PATTERN = /(\d+\.\d+\.\d+)/;
function extractSemver(value) {
  const match = value.match(SEMVER_PATTERN);
  return match?.[1] ?? null;
}
function isVersionOutdated(current, target) {
  const currentParts = current.split(".").map(Number);
  const targetParts = target.split(".").map(Number);
  for (let index = 0; index < Math.max(currentParts.length, targetParts.length); index += 1) {
    const currentPart = currentParts[index] ?? 0;
    const targetPart = targetParts[index] ?? 0;
    if (currentPart < targetPart) {
      return true;
    }
    if (currentPart > targetPart) {
      return false;
    }
  }
  return false;
}

// 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 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;
}

// src/platform/app/self-update.ts
var JU_HONG_E_PACKAGE_NAME = "sales-frontend-ju-hong-e";
var SELF_UPDATE_SKIP_ENV_NAME = "JU_HONG_E_SKIP_SELF_UPDATE";
var SELF_UPDATE_LABEL = "ju-hong-e";
function createSelfUpdateStepMessage(step, detail) {
  const suffix = detail ? ` (${detail})` : "";
  switch (step) {
    case "start":
      return `[${SELF_UPDATE_LABEL}] \uBCF8\uCCB4 \uC0C1\uD0DC\uB97C \uC810\uAC80\uD558\uACE0 \uC788\uC2B5\uB2C8\uB2E4...`;
    case "install-ok":
      return `  + \uBCF8\uCCB4 \uC124\uCE58 \uD655\uC778${suffix}`;
    case "version-current":
      return `  + \uD604\uC7AC \uBC84\uC804 \uD655\uC778${suffix}`;
    case "version-skip":
      return `  + \uAC15\uC81C \uC5C5\uB370\uC774\uD2B8 \uB300\uC0C1\uC774 \uC544\uB2C8\uC5B4\uC11C \uD604\uC7AC \uBC84\uC804\uC73C\uB85C \uC9C4\uD589\uD569\uB2C8\uB2E4.${suffix}`;
    case "version-disabled":
      return `  + minimumVersion \uB300\uC0C1\uC774\uC9C0\uB9CC \uAC15\uC81C \uC5C5\uB370\uC774\uD2B8 \uC124\uC815(enabled=false)\uC774\uB77C \uD604\uC7AC \uBC84\uC804\uC73C\uB85C \uC9C4\uD589\uD569\uB2C8\uB2E4.${suffix}`;
    case "version-satisfied":
      return `  + \uBCF8\uCCB4 \uAC15\uC81C \uC5C5\uB370\uC774\uD2B8 \uAE30\uC900\uC744 \uCDA9\uC871\uD574 \uD604\uC7AC \uBC84\uC804\uC73C\uB85C \uC9C4\uD589\uD569\uB2C8\uB2E4.${suffix}`;
    case "version-updating":
      return `  ~ \uBCF8\uCCB4 \uC5C5\uB370\uC774\uD2B8 \uC911...${suffix}`;
    case "version-update-ok":
      return `  + \uBCF8\uCCB4 \uC5C5\uB370\uC774\uD2B8 \uC644\uB8CC${suffix}`;
    case "version-update-failed":
      return `  ! \uBCF8\uCCB4 \uC5C5\uB370\uC774\uD2B8\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.${suffix}`;
    default:
      return "";
  }
}
function validateSelfUpdate(binaryName, parsedArgs, trace) {
  trace("self-update:validate:start", binaryName);
  if (parsedArgs.testMode) {
    trace("self-update:validate:skip:test-mode");
    return {
      ok: true,
      status: "skipped"
    };
  }
  if (process.env[SELF_UPDATE_SKIP_ENV_NAME] === "1") {
    trace("self-update:validate:skip:env", SELF_UPDATE_SKIP_ENV_NAME);
    return {
      ok: true,
      status: "skipped"
    };
  }
  console.log(createSelfUpdateStepMessage("start"));
  const currentVersion = extractSemver("0.5.0");
  if (!currentVersion) {
    trace("self-update:validate:skip:current-version-missing", "0.5.0");
    return {
      ok: true,
      status: "skipped"
    };
  }
  console.log(createSelfUpdateStepMessage("install-ok", `v${currentVersion}`));
  console.log(createSelfUpdateStepMessage("version-current", `v${currentVersion}`));
  const policy = getPackageForceUpdatePolicy(JU_HONG_E_PACKAGE_NAME, trace);
  if (!policy?.enabled || !policy.minimumVersion) {
    const skipStep = !policy?.enabled && policy?.minimumVersion ? "version-disabled" : "version-skip";
    trace(
      "self-update:validate:skip:policy",
      JSON.stringify({
        enabled: policy?.enabled ?? false,
        minimumVersion: policy?.minimumVersion ?? ""
      })
    );
    console.log(
      createSelfUpdateStepMessage(
        skipStep,
        `\uD604\uC7AC v${currentVersion}${policy?.minimumVersion ? `, minimumVersion v${policy.minimumVersion}` : ""}`
      )
    );
    return {
      ok: true,
      status: "ready"
    };
  }
  if (!isVersionOutdated(currentVersion, policy.minimumVersion)) {
    trace("self-update:validate:satisfied", `${currentVersion} >= ${policy.minimumVersion}`);
    console.log(
      createSelfUpdateStepMessage(
        "version-satisfied",
        `\uD604\uC7AC v${currentVersion}, minimumVersion v${policy.minimumVersion}`
      )
    );
    return {
      ok: true,
      status: "ready"
    };
  }
  console.log(
    createSelfUpdateStepMessage("version-updating", `${currentVersion} -> ${policy.minimumVersion}`)
  );
  const updated = upgradeJuHongEPackage(policy.minimumVersion, trace);
  if (!updated) {
    trace("self-update:validate:update-failed", `${currentVersion} -> ${policy.minimumVersion}`);
    console.log(createSelfUpdateStepMessage("version-update-failed", `${currentVersion} -> ${policy.minimumVersion}`));
    return {
      message: [
        "[ju-hong-e] \uC140\uD504 \uC5C5\uB370\uC774\uD2B8\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
        "",
        `\uD604\uC7AC \uBC84\uC804: v${currentVersion}`,
        `\uCD5C\uC18C \uC694\uAD6C \uBC84\uC804: v${policy.minimumVersion}`,
        "",
        "\uB2E4\uC74C \uBA85\uB839\uC5B4\uB85C \uC9C1\uC811 \uC5C5\uB370\uC774\uD2B8\uD55C \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC8FC\uC138\uC694:",
        `  $ npm install -g ${JU_HONG_E_PACKAGE_NAME}@${policy.minimumVersion}`
      ].join("\n"),
      ok: false,
      status: "update-failed"
    };
  }
  trace("self-update:validate:updated", `${currentVersion} -> ${policy.minimumVersion}`);
  console.log(createSelfUpdateStepMessage("version-update-ok", `v${policy.minimumVersion}`));
  return {
    message: [
      "[ju-hong-e] \uC140\uD504 \uC5C5\uB370\uC774\uD2B8\uB97C \uC644\uB8CC\uD588\uC2B5\uB2C8\uB2E4.",
      "",
      `\uC801\uC6A9 \uBC84\uC804: v${policy.minimumVersion}`,
      `${binaryName} \uB97C \uB2E4\uC2DC \uC2E4\uD589\uD574 \uC0C8 \uBC84\uC804\uC73C\uB85C \uC2DC\uC791\uD574 \uC8FC\uC138\uC694:`,
      `  $ ${binaryName}`
    ].join("\n"),
    ok: false,
    status: "updated"
  };
}
function upgradeJuHongEPackage(minimumVersion, trace) {
  const packageSpec = `${JU_HONG_E_PACKAGE_NAME}@${minimumVersion}`;
  trace("self-update:upgrade:start", packageSpec);
  const result = spawnSync("npm", ["install", "-g", packageSpec], {
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 20,
    stdio: "inherit"
  });
  if (result.error || result.status !== 0) {
    trace("self-update:upgrade:failed", getErrorSummary(result.error || result.stderr || result.status));
    return false;
  }
  trace("self-update:upgrade:done", packageSpec);
  return true;
}

export { validateSelfUpdate };
