import type { VitalsReporter } from '@platform-modules/perf-react';
import * as Sentry from '@sentry/astro';

type ScopeLike = {
  setTag?: (key: string, value: string) => void;
  setMeasurement?: (name: string, value: number) => void;
};

const DYNAMIC_SEGMENT =
  /^(?:\d+|[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9_-]{8,})$/i;

function sanitizeRoute(route: string): string {
  const path = route.split(/[?#]/, 1)[0] || '/';
  const segments = path.split('/').map((segment) => {
    if (!segment || !DYNAMIC_SEGMENT.test(segment)) return segment;
    return ':id';
  });
  const sanitized = segments.join('/');
  return sanitized.startsWith('/') ? sanitized : `/${sanitized}`;
}

function annotateScope(scope: ScopeLike, route: string, name: string, value: number): void {
  scope.setTag?.('route', route);
  scope.setMeasurement?.(name, value);
}

export const sentryReporter: VitalsReporter = {
  report(metric) {
    const route = sanitizeRoute(metric.route);

    Sentry.addBreadcrumb({
      category: 'web-vital',
      level: 'info',
      message: metric.name,
      data: {
        route,
        name: metric.name,
        value: metric.value,
        rating: metric.rating,
      },
    });

    const currentScope = Sentry.getCurrentScope?.() as ScopeLike | undefined;
    if (currentScope) {
      annotateScope(currentScope, route, metric.name, metric.value);
      return;
    }

    Sentry.withScope?.((scope) =>
      annotateScope(scope as ScopeLike, route, metric.name, metric.value),
    );
  },
};
