/**
 * useMlOverlayData Hook
 * Custom hook for fetching and caching ML overlay data for trading charts
 * Uses TanStack Query for efficient data fetching and caching
 */

import { useQuery } from '@tanstack/react-query';
import type {
  MLPrediction,
  SignalMarker,
  ICTConcept,
  MLPredictionResponse,
} from '../../types/mlOverlay.types';

// ============================================================================
// Constants
// ============================================================================

const ML_API_URL = import.meta.env.VITE_ML_URL || 'http://localhost:3083';
const STALE_TIME = 60000; // 60 seconds
const CACHE_TIME = 300000; // 5 minutes

// ============================================================================
// API Functions
// ============================================================================

async function fetchMLPredictions(
  symbol: string,
  timeframe: string
): Promise<MLPredictionResponse> {
  const response = await fetch(
    `${ML_API_URL}/api/ml/predictions/${symbol}/${timeframe}`
  );

  if (!response.ok) {
    throw new Error(`Failed to fetch ML predictions: ${response.statusText}`);
  }

  return response.json();
}

// ============================================================================
// Hook
// ============================================================================

export interface UseMlOverlayDataOptions {
  symbol: string;
  timeframe: string;
  enabled?: boolean;
}

export interface UseMlOverlayDataResult {
  predictions: MLPrediction[];
  signals: SignalMarker[];
  ictConcepts: ICTConcept[];
  isLoading: boolean;
  error: Error | null;
  refetch: () => void;
}

export function useMlOverlayData({
  symbol,
  timeframe,
  enabled = true,
}: UseMlOverlayDataOptions): UseMlOverlayDataResult {
  const {
    data,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['ml-predictions', symbol, timeframe],
    queryFn: () => fetchMLPredictions(symbol, timeframe),
    staleTime: STALE_TIME,
    gcTime: CACHE_TIME,
    enabled,
    retry: 2,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10000),
  });

  return {
    predictions: data?.predictions || [],
    signals: data?.signals || [],
    ictConcepts: data?.ictConcepts || [],
    isLoading,
    error: error as Error | null,
    refetch,
  };
}

export default useMlOverlayData;
