import { createQuery } from '@tanstack/svelte-query';
import { api } from './client';

// Mirrors internal/api/me_recommendation_metrics.go: raw play sources are
// bucketed server-side into stable surface families, grouped by intent, and
// anchored by the manual-plays baseline (milestone #127).
// A difference from the baseline, with its uncertainty (#2495). Both figures
// are already in percentage points — the server does the arithmetic so both
// clients read the same numbers.
//
// `distinguishable: false` means |delta_pp| < margin_pp: the delta cannot be
// told apart from zero, however large it looks. That distinction is the whole
// point of this type — `low_confidence` answers "is this worth showing?", which
// is a much lower bar than "is this worth acting on?".
export type MetricDelta = {
  delta_pp: number;
  margin_pp: number;
  distinguishable: boolean;
};

export type SurfaceMetric = {
  key: string;
  label: string;
  plays: number;
  skips: number;
  skip_rate: number;
  avg_completion: number;
  low_confidence: boolean;
  // Absent on the baseline row itself, and whenever the samples are too thin
  // for a margin to mean anything.
  skip_delta?: MetricDelta;
  completion_delta?: MetricDelta;
  // Present when the surface's builder stamps pick-kind provenance and
  // the window holds attributed plays (#1249, generalized #1270): For
  // You's taste/fresh split, Discover's candidate buckets, the tiered
  // mixes' tier1-3 — plus pre-attribution plays.
  breakdown?: SurfaceMetric[];
};

export type SurfaceIntent = 'go_to' | 'discovery' | 'direct';

export type SurfaceGroup = {
  intent: SurfaceIntent;
  label: string;
  surfaces: SurfaceMetric[];
};

export type RecommendationMetrics = {
  window_days: number;
  baseline: SurfaceMetric | null;
  groups: SurfaceGroup[];
};

export function getRecommendationMetrics(): Promise<RecommendationMetrics> {
  return api.get<RecommendationMetrics>('/api/me/recommendation-metrics');
}

export const REC_METRICS_QUERY_KEY = ['settings', 'recommendation-metrics'] as const;

export function createRecommendationMetricsQuery() {
  return createQuery({
    queryKey: REC_METRICS_QUERY_KEY,
    queryFn: getRecommendationMetrics,
    staleTime: 60_000
  });
}
