export async function uploadTelemetryArtifact(telemetry, artifact) {
  if (!telemetry?.enabled) return { skipped: true, reason: "disabled" };
  if (process.env.TESTKIT_TELEMETRY === "0") {
    return { skipped: true, reason: "disabled-by-env" };
  }
  if (!telemetry.endpoint) {
    return { skipped: true, reason: "missing-endpoint" };
  }
  if (!telemetry.tokenEnv) {
    return { skipped: true, reason: "missing-token-env" };
  }

  const token = process.env[telemetry.tokenEnv];
  if (!token) {
    return { skipped: true, reason: "missing-token" };
  }

  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), telemetry.timeoutMs || 3_000);

  try {
    const response = await fetch(telemetry.endpoint, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(artifact),
      signal: controller.signal,
    });

    if (!response.ok) {
      const body = await response.text().catch(() => "");
      throw new Error(
        `telemetry upload failed with ${response.status}${body ? `: ${body.trim()}` : ""}`
      );
    }

    return { skipped: false, ok: true };
  } finally {
    clearTimeout(timeout);
  }
}
