import * as Chunk from "@effect/data/Chunk";
import * as Duration from "@effect/data/Duration";
import { dual } from "@effect/data/Function";
import * as HashMap from "@effect/data/HashMap";
import * as number from "@effect/data/Number";
import * as Option from "@effect/data/Option";
import * as metricState from "@effect/io/internal_effect_untraced/metric/state";
/** @internal */
const MetricHookSymbolKey = "@effect/io/Metric/Hook";
/** @internal */
export const MetricHookTypeId = /*#__PURE__*/Symbol.for(MetricHookSymbolKey);
/** @internal */
const metricHookVariance = {
  _In: _ => _,
  _Out: _ => _
};
/** @internal */
export const make = (get, update) => {
  return {
    [MetricHookTypeId]: metricHookVariance,
    update,
    get
  };
};
/** @internal */
export const onUpdate = /*#__PURE__*/dual(2, (self, f) => ({
  [MetricHookTypeId]: metricHookVariance,
  get: self.get,
  update: input => {
    self.update(input);
    return f(input);
  }
}));
/** @internal */
export const counter = _key => {
  let sum = 0;
  return make(() => metricState.counter(sum), value => {
    sum = sum + value;
  });
};
/** @internal */
export const frequency = _key => {
  let count = 0;
  const values = new Map();
  const update = word => {
    count = count + 1;
    const slotCount = values.get(word) ?? 0;
    values.set(word, slotCount + 1);
  };
  const snapshot = () => HashMap.fromIterable(values.entries());
  return make(() => metricState.frequency(snapshot()), update);
};
/** @internal */
export const gauge = (_key, startAt) => {
  let value = startAt;
  return make(() => metricState.gauge(value), v => {
    value = v;
  });
};
/** @internal */
export const histogram = key => {
  const bounds = key.keyType.boundaries.values;
  const size = bounds.length;
  const values = new Uint32Array(size + 1);
  const boundaries = new Float32Array(size);
  let count = 0;
  let sum = 0;
  let min = Number.MAX_VALUE;
  let max = Number.MIN_VALUE;
  Chunk.mapWithIndex((n, i) => {
    boundaries[i] = n;
  })(Chunk.sort(number.Order)(bounds));
  // Insert the value into the right bucket with a binary search
  const update = value => {
    let from = 0;
    let to = size;
    while (from !== to) {
      const mid = Math.floor(from + (to - from) / 2);
      const boundary = boundaries[mid];
      if (value <= boundary) {
        to = mid;
      } else {
        from = mid;
      }
      // The special case when to / from have a distance of one
      if (to === from + 1) {
        if (value <= boundaries[from]) {
          to = from;
        } else {
          from = to;
        }
      }
    }
    values[from] = values[from] + 1;
    count = count + 1;
    sum = sum + value;
    if (value < min) {
      min = value;
    }
    if (value > max) {
      max = value;
    }
  };
  const getBuckets = () => {
    const builder = Array(size);
    let cumulated = 0;
    for (let i = 0; i < size; i++) {
      const boundary = boundaries[i];
      const value = values[i];
      cumulated = cumulated + value;
      builder[i] = [boundary, cumulated];
    }
    return Chunk.unsafeFromArray(builder);
  };
  return make(() => metricState.histogram(getBuckets(), count, min, max, sum), update);
};
/** @internal */
export const summary = key => {
  const {
    error,
    maxAge,
    maxSize,
    quantiles
  } = key.keyType;
  const sortedQuantiles = Chunk.sort(number.Order)(quantiles);
  const values = Array(maxSize);
  let head = 0;
  let count = 0;
  let sum = 0;
  let min = Number.MAX_VALUE;
  let max = Number.MIN_VALUE;
  // Just before the snapshot we filter out all values older than maxAge
  const snapshot = now => {
    const builder = [];
    // If the buffer is not full yet it contains valid items at the 0..last
    // indices and null values at the rest of the positions.
    //
    // If the buffer is already full then all elements contains a valid
    // measurement with timestamp.
    //
    // At any given point in time we can enumerate all the non-null elements in
    // the buffer and filter them by timestamp to get a valid view of a time
    // window.
    //
    // The order does not matter because it gets sorted before passing to
    // `calculateQuantiles`.
    let i = 0;
    while (i !== maxSize - 1) {
      const item = values[i];
      if (item != null) {
        const [t, v] = item;
        const age = Duration.millis(now - t);
        if (age.millis >= 0 && age <= maxAge) {
          builder.push(v);
        }
      }
      i = i + 1;
    }
    return calculateQuantiles(error, sortedQuantiles, Chunk.sort(number.Order)(Chunk.unsafeFromArray(builder)));
  };
  const observe = (value, timestamp) => {
    if (maxSize > 0) {
      head = head + 1;
      const target = head % maxSize;
      values[target] = [timestamp, value];
    }
    count = count + 1;
    sum = sum + value;
    if (value < min) {
      min = value;
    }
    if (value > max) {
      max = value;
    }
  };
  return make(() => metricState.summary(error, snapshot(Date.now()), count, min, max, sum), ([value, timestamp]) => observe(value, timestamp));
};
/** @internal */
const calculateQuantiles = (error, sortedQuantiles, sortedSamples) => {
  // The number of samples examined
  const sampleCount = sortedSamples.length;
  if (Chunk.isEmpty(sortedQuantiles)) {
    return Chunk.empty();
  }
  const head = Chunk.unsafeHead(sortedQuantiles);
  const tail = Chunk.drop(1)(sortedQuantiles);
  const resolved = Chunk.reduce(Chunk.of(resolveQuantile(error, sampleCount, Option.none(), 0, head, sortedSamples)), (accumulator, quantile) => {
    const h = Chunk.unsafeHead(accumulator);
    return Chunk.append(resolveQuantile(error, sampleCount, h.value, h.consumed, quantile, h.rest))(accumulator);
  })(tail);
  return Chunk.map(rq => [rq.quantile, rq.value])(resolved);
};
/** @internal */
const resolveQuantile = (error, sampleCount, current, consumed, quantile, rest) => {
  let error_1 = error;
  let sampleCount_1 = sampleCount;
  let current_1 = current;
  let consumed_1 = consumed;
  let quantile_1 = quantile;
  let rest_1 = rest;
  let error_2 = error;
  let sampleCount_2 = sampleCount;
  let current_2 = current;
  let consumed_2 = consumed;
  let quantile_2 = quantile;
  let rest_2 = rest;
  // eslint-disable-next-line no-constant-condition
  while (1) {
    // If the remaining list of samples is empty, there is nothing more to resolve
    if (Chunk.isEmpty(rest_1)) {
      return {
        quantile: quantile_1,
        value: Option.none(),
        consumed: consumed_1,
        rest: Chunk.empty()
      };
    }
    // If the quantile is the 100% quantile, we can take the maximum of all the
    // remaining values as the result
    if (quantile_1 === 1) {
      return {
        quantile: quantile_1,
        value: Option.some(Chunk.unsafeLast(rest_1)),
        consumed: consumed_1 + rest_1.length,
        rest: Chunk.empty()
      };
    }
    // Split into two chunks - the first chunk contains all elements of the same
    // value as the chunk head
    const sameHead = Chunk.splitWhere(n => n > Chunk.unsafeHead(rest_1))(rest_1);
    // How many elements do we want to accept for this quantile
    const desired = quantile_1 * sampleCount_1;
    // The error margin
    const allowedError = error_1 / 2 * desired;
    // Taking into account the elements consumed from the samples so far and the
    // number of same elements at the beginning of the chunk, calculate the number
    // of elements we would have if we selected the current head as result
    const candConsumed = consumed_1 + sameHead[0].length;
    const candError = Math.abs(candConsumed - desired);
    // If we haven't got enough elements yet, recurse
    if (candConsumed < desired - allowedError) {
      error_2 = error_1;
      sampleCount_2 = sampleCount_1;
      current_2 = Chunk.head(rest_1);
      consumed_2 = candConsumed;
      quantile_2 = quantile_1;
      rest_2 = sameHead[1];
      error_1 = error_2;
      sampleCount_1 = sampleCount_2;
      current_1 = current_2;
      consumed_1 = consumed_2;
      quantile_1 = quantile_2;
      rest_1 = rest_2;
      continue;
    }
    // If we have too many elements, select the previous value and hand back the
    // the rest as leftover
    if (candConsumed > desired + allowedError) {
      return {
        quantile: quantile_1,
        value: current_1,
        consumed: consumed_1,
        rest: rest_1
      };
    }
    // If we are in the target interval, select the current head and hand back the leftover after dropping all elements
    // from the sample chunk that are equal to the current head
    switch (current_1._tag) {
      case "None":
        {
          error_2 = error_1;
          sampleCount_2 = sampleCount_1;
          current_2 = Chunk.head(rest_1);
          consumed_2 = candConsumed;
          quantile_2 = quantile_1;
          rest_2 = sameHead[1];
          error_1 = error_2;
          sampleCount_1 = sampleCount_2;
          current_1 = current_2;
          consumed_1 = consumed_2;
          quantile_1 = quantile_2;
          rest_1 = rest_2;
          continue;
        }
      case "Some":
        {
          const prevError = Math.abs(desired - current_1.value);
          if (candError < prevError) {
            error_2 = error_1;
            sampleCount_2 = sampleCount_1;
            current_2 = Chunk.head(rest_1);
            consumed_2 = candConsumed;
            quantile_2 = quantile_1;
            rest_2 = sameHead[1];
            error_1 = error_2;
            sampleCount_1 = sampleCount_2;
            current_1 = current_2;
            consumed_1 = consumed_2;
            quantile_1 = quantile_2;
            rest_1 = rest_2;
            continue;
          }
          return {
            quantile: quantile_1,
            value: Option.some(current_1.value),
            consumed: consumed_1,
            rest: rest_1
          };
        }
    }
  }
  throw new Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/io/issues");
};
//# sourceMappingURL=hook.mjs.map