'use client';

/**
 * Event logger class to wrap Segment and make it easy to replace in the future.
 */
import {
  AnalyticsBrowser,
  AnalyticsBrowserSettings,
} from '@segment/analytics-next';

import { isProd } from '@/utils/environment';

import PreInitQueue from './PreInitQueue';

// This is a static file needed to init the segment client. we already have this for the existing client
// as mockIntegrationResponseTemplate in suno-cdk/lib/event-stream-stack/api-gateway/event-logger-api-gateway.ts
const CDN_SETTINGS = {
  integrations: {
    'Segment.io': {
      apiKey: 'suno',
      host: '',
      unbundledIntegrations: [],
      addBundledMetadata: true,
      maybeBundledConfigIds: {},
      versionSettings: {
        version: '4.4.7',
        componentTypes: ['browser'],
      },
      retryQueue: true,
    },
  },
  plan: {
    track: {
      __default: {
        enabled: true,
        integrations: {},
      },
    },
    identify: {
      __default: {
        enabled: true,
      },
    },
    group: {
      __default: {
        enabled: true,
      },
    },
  },
  edgeFunction: {},
  enabledMiddleware: {},
  metrics: {
    sampleRate: 0.1,
  },
  legacyVideoPluginsEnabled: false,
  remotePlugins: [],
};

const SEGMENT_SETTINGS = {
  writeKey: 'suno',
  cdnSettings: CDN_SETTINGS as AnalyticsBrowserSettings['cdnSettings'],
};

export function getDomains(analyticsBaseUrl: string) {
  const hostname =
    typeof window !== 'undefined' ? window.location.hostname : '';
  const METRICS_ENDPOINT = 'agg-receiver-service/v1/events';

  let DOMAIN_BASE_FRAGMENT_URL = 'bkz9921ndc.execute-api.us-east-2.amazonaws';
  let DOMAIN_BASE_FRAGMENT = `https://${DOMAIN_BASE_FRAGMENT_URL}.com`;
  let DOMAIN_BASE = `${DOMAIN_BASE_FRAGMENT}/dev-testing/${METRICS_ENDPOINT}`;
  let DOMAIN_BASE_WITHOUT_PROTOCOL = DOMAIN_BASE.split('://')[1];

  // if the analyticsBaseUrl is the same, use the dev settings
  if (
    analyticsBaseUrl &&
    analyticsBaseUrl.length > 0 &&
    DOMAIN_BASE_FRAGMENT_URL !== analyticsBaseUrl
  ) {
    DOMAIN_BASE_FRAGMENT_URL = analyticsBaseUrl;
    DOMAIN_BASE_FRAGMENT = `https://${DOMAIN_BASE_FRAGMENT_URL}.com`;
    DOMAIN_BASE = `${DOMAIN_BASE_FRAGMENT}/${METRICS_ENDPOINT}`;
    DOMAIN_BASE_WITHOUT_PROTOCOL = DOMAIN_BASE.split('://')[1];
  } else if (hostname.endsWith('.com')) {
    DOMAIN_BASE_FRAGMENT_URL = 'm-stratovibe.prod.suno';
    DOMAIN_BASE_FRAGMENT = `https://${DOMAIN_BASE_FRAGMENT_URL}.com`;
    DOMAIN_BASE = `${DOMAIN_BASE_FRAGMENT}/${METRICS_ENDPOINT}`;
    DOMAIN_BASE_WITHOUT_PROTOCOL = DOMAIN_BASE.split('://')[1];
  } else if (isProd) {
    DOMAIN_BASE_FRAGMENT_URL = 'm-stratovibe.staging.suno';
    DOMAIN_BASE_FRAGMENT = `https://${DOMAIN_BASE_FRAGMENT_URL}.com`;
    DOMAIN_BASE = `${DOMAIN_BASE_FRAGMENT}/${METRICS_ENDPOINT}`;
    DOMAIN_BASE_WITHOUT_PROTOCOL = DOMAIN_BASE.split('://')[1];
  }
  return {
    DOMAIN_BASE_FRAGMENT,
    DOMAIN_BASE_FRAGMENT_URL,
    DOMAIN_BASE,
    DOMAIN_BASE_WITHOUT_PROTOCOL,
  };
}

const clientQueue = new PreInitQueue<AnalyticsBrowser>();
const homePageClientQueue = new PreInitQueue<AnalyticsBrowser>();

// Module-level cache for current pathname
// Updated by AnalyticsContext via updateCachedPathname()
let cachedPathname: string | undefined;

export const updateCachedPathnameForSegment = (pathname: string) => {
  cachedPathname = pathname;
};

export const initializeSegmentClient = (analyticsBaseUrl: string) => {
  const { DOMAIN_BASE_WITHOUT_PROTOCOL } = getDomains(analyticsBaseUrl);

  const deliveryStrategy = {
    deliveryStrategy: {
      strategy: 'batching' as const,
      config: {
        // max batch size
        size: 150,
        // max timeout before sending batch
        timeout: 10000,
        maxRetries: 3,
      },
    },
  };

  clientQueue.receiveDependency(
    new AnalyticsBrowser().load(SEGMENT_SETTINGS, {
      integrations: {
        'Segment.io': {
          apiHost: DOMAIN_BASE_WITHOUT_PROTOCOL,
          protocol: 'https',
          ...deliveryStrategy,
        },
      },
    })
  );
};

export const initializeHomePageSegmentClient = (analyticsBaseUrl: string) => {
  const { DOMAIN_BASE_WITHOUT_PROTOCOL } = getDomains(analyticsBaseUrl);

  homePageClientQueue.receiveDependency(
    new AnalyticsBrowser().load(SEGMENT_SETTINGS, {
      integrations: {
        'Segment.io': {
          apiHost: DOMAIN_BASE_WITHOUT_PROTOCOL,
          protocol: 'https',
        },
      },
    })
  );
};

// TODO: need to set up CORS / batch endpoints
// https://linear.app/sunomusic/issue/WEB-1031/setup-batch-client-for-new-segment-sdk
export const track = (name: string, properties: Record<string, any>) => {
  // Use cached pathname from Next.js router, fall back to window.location
  const pathname =
    cachedPathname ??
    (typeof window !== 'undefined' ? window.location.pathname : undefined);

  const isHomePage = pathname === '/home';

  // Route to the appropriate client based on page
  const queue = isHomePage ? homePageClientQueue : clientQueue;

  queue.runWithDependency((segmentClient) =>
    segmentClient.track(name, properties)
  );
};

export const getAnonymousId = async () => {
  return await clientQueue.runWithDependency((segmentClient) =>
    segmentClient.instance?.user().anonymousId()
  );
};
