import { _optionalChain } from '@sentry/utils';
import { IORedisInstrumentation } from '@opentelemetry/instrumentation-ioredis';
import { RedisInstrumentation } from '@opentelemetry/instrumentation-redis-4';
import { defineIntegration, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, SEMANTIC_ATTRIBUTE_CACHE_HIT, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_CACHE_KEY, spanToJSON } from '@sentry/core';
import { truncate } from '@sentry/utils';
import { generateInstrumentOnce } from '../../otel/instrument.js';
import { getCacheKeySafely, getCacheOperation, shouldConsiderForCache, calculateCacheItemSize, isInCommands, GET_COMMANDS } from '../../utils/redisCache.js';

const INTEGRATION_NAME = 'Redis';

let _redisOptions = {};

const cacheResponseHook = (span, redisCommand, cmdArgs, response) => {
  span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.otel.redis');

  const safeKey = getCacheKeySafely(redisCommand, cmdArgs);
  const cacheOperation = getCacheOperation(redisCommand);

  if (
    !safeKey ||
    !cacheOperation ||
    !_optionalChain([_redisOptions, 'optionalAccess', _ => _.cachePrefixes]) ||
    !shouldConsiderForCache(redisCommand, safeKey, _redisOptions.cachePrefixes)
  ) {
    // not relevant for cache
    return;
  }

  // otel/ioredis seems to be using the old standard, as there was a change to those params: https://github.com/open-telemetry/opentelemetry-specification/issues/3199
  // We are using params based on the docs: https://opentelemetry.io/docs/specs/semconv/attributes-registry/network/
  const networkPeerAddress = _optionalChain([spanToJSON, 'call', _2 => _2(span), 'access', _3 => _3.data, 'optionalAccess', _4 => _4['net.peer.name']]);
  const networkPeerPort = _optionalChain([spanToJSON, 'call', _5 => _5(span), 'access', _6 => _6.data, 'optionalAccess', _7 => _7['net.peer.port']]);
  if (networkPeerPort && networkPeerAddress) {
    span.setAttributes({ 'network.peer.address': networkPeerAddress, 'network.peer.port': networkPeerPort });
  }

  const cacheItemSize = calculateCacheItemSize(response);

  if (cacheItemSize) {
    span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);
  }

  if (isInCommands(GET_COMMANDS, redisCommand) && cacheItemSize !== undefined) {
    span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);
  }

  span.setAttributes({
    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,
    [SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey,
  });

  const spanDescription = safeKey.join(', ');

  span.updateName(truncate(spanDescription, 1024));
};

const instrumentIORedis = generateInstrumentOnce('IORedis', () => {
  return new IORedisInstrumentation({
    responseHook: cacheResponseHook,
  });
});

const instrumentRedis4 = generateInstrumentOnce('Redis-4', () => {
  return new RedisInstrumentation({
    responseHook: cacheResponseHook,
  });
});

/** To be able to preload all Redis OTel instrumentations with just one ID ("Redis"), all the instrumentations are generated in this one function  */
const instrumentRedis = Object.assign(
  () => {
    instrumentIORedis();
    instrumentRedis4();

    // todo: implement them gradually
    // new LegacyRedisInstrumentation({}),
  },
  { id: INTEGRATION_NAME },
);

const _redisIntegration = ((options = {}) => {
  return {
    name: INTEGRATION_NAME,
    setupOnce() {
      _redisOptions = options;
      instrumentRedis();
    },
  };
}) ;

/**
 * Redis integration for "ioredis"
 *
 * Capture tracing data for redis and ioredis.
 */
const redisIntegration = defineIntegration(_redisIntegration);

export { instrumentRedis, redisIntegration };
