All files / src/hooks useAiAnalysis.ts

100% Statements 56/56
91.3% Branches 21/23
100% Functions 7/7
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186                              1x                                       40x 40x 40x   19x           9x                 3x                         1x           5x           1x   1x   1x                       1x           38x   38x   17x 17x   17x   8x 5x 5x     4x 4x 4x     1x 1x 1x     2x 1x 1x 1x 1x     1x 1x 1x       4x 4x 4x           38x 3x 3x 1x 1x   2x 2x 2x 1x   1x   1x     1x       38x 1x     38x 1x     38x 38x                    
import { useReducer, useCallback, useMemo } from 'react';
import {
  Flyer,
  FlyerItem,
  MasterGroceryItem,
  AnalysisType,
  AiAnalysisState,
  AiAnalysisAction,
} from '../types';
import { AiAnalysisService } from '../services/aiAnalysisService';
import { logger } from '../services/logger.client';
 
/**
 * The initial state for the AI analysis reducer.
 */
const initialState: AiAnalysisState = {
  loadingAnalysis: null,
  error: null,
  results: {},
  sources: {},
  generatedImageUrl: null,
};
 
/**
 * A reducer function to manage the complex state of the AI analysis panel.
 * It handles loading, success, and error states for multiple types of analysis.
 * @param state - The current state.
 * @param action - The action to perform.
 * @returns The new state.
 */
export function aiAnalysisReducer(
  state: AiAnalysisState,
  action: AiAnalysisAction,
): AiAnalysisState {
  // Safely log the payload only if it exists on the action.
  const payload = 'payload' in action ? action.payload : {};
  logger.info(`[aiAnalysisReducer] Dispatched action: ${action.type}`, { payload });
  switch (action.type) {
    case 'FETCH_START':
      return {
        ...state,
        loadingAnalysis: action.payload.analysisType,
        error: null, // Clear previous errors on a new request
      };
    case 'FETCH_SUCCESS_TEXT':
      return {
        ...state,
        loadingAnalysis: null,
        results: {
          ...state.results,
          [action.payload.analysisType]: action.payload.data,
        },
      };
    case 'FETCH_SUCCESS_GROUNDED':
      return {
        ...state,
        loadingAnalysis: null,
        results: {
          ...state.results,
          [action.payload.analysisType]: action.payload.data.text,
        },
        sources: {
          ...state.sources,
          [action.payload.analysisType]: action.payload.data.sources,
        },
      };
    case 'FETCH_SUCCESS_IMAGE':
      return {
        ...state,
        loadingAnalysis: null,
        generatedImageUrl: `data:image/png;base64,${action.payload.data}`,
      };
    case 'FETCH_ERROR':
      return {
        ...state,
        loadingAnalysis: null,
        error: action.payload.error,
      };
    case 'CLEAR_ERROR':
      return { ...state, error: null };
    case 'RESET_STATE':
      return initialState;
    default:
      return state;
  }
}
 
interface UseAiAnalysisParams {
  flyerItems: FlyerItem[];
  selectedFlyer: Flyer | null;
  watchedItems: MasterGroceryItem[];
  // The service is now a required dependency.
  service: AiAnalysisService;
}
 
export const useAiAnalysis = ({
  flyerItems,
  selectedFlyer,
  watchedItems,
  service,
}: UseAiAnalysisParams) => {
  const [state, dispatch] = useReducer(aiAnalysisReducer, initialState);
 
  const runAnalysis = useCallback(
    async (analysisType: AnalysisType) => {
      dispatch({ type: 'FETCH_START', payload: { analysisType } });
      try {
        // Delegate the call to the injected service.
        switch (analysisType) {
          case AnalysisType.QUICK_INSIGHTS: {
            const data = await service.getQuickInsights(flyerItems);
            dispatch({ type: 'FETCH_SUCCESS_TEXT', payload: { analysisType, data } });
            break;
          }
          case AnalysisType.DEEP_DIVE: {
            const data = await service.getDeepDiveAnalysis(flyerItems);
            dispatch({ type: 'FETCH_SUCCESS_TEXT', payload: { analysisType, data } });
            break;
          }
          case AnalysisType.WEB_SEARCH: {
            const data = await service.searchWeb(flyerItems);
            dispatch({ type: 'FETCH_SUCCESS_GROUNDED', payload: { analysisType, data } });
            break;
          }
          case AnalysisType.PLAN_TRIP: {
            if (!selectedFlyer?.store)
              throw new Error('Store information is not available for trip planning.');
            const data = await service.planTripWithMaps(flyerItems, selectedFlyer.store);
            dispatch({ type: 'FETCH_SUCCESS_GROUNDED', payload: { analysisType, data } });
            break;
          }
          case AnalysisType.COMPARE_PRICES: {
            const data = await service.compareWatchedItemPrices(watchedItems);
            dispatch({ type: 'FETCH_SUCCESS_GROUNDED', payload: { analysisType, data } });
            break;
          }
        }
      } catch (err: unknown) {
        logger.error(`runAnalysis failed for type ${analysisType}`, { error: err });
        const message = err instanceof Error ? err.message : 'An unexpected error occurred.';
        dispatch({ type: 'FETCH_ERROR', payload: { error: message } });
      }
    },
    [service, flyerItems, watchedItems, selectedFlyer],
  );
 
  const generateImage = useCallback(async () => {
    const mealPlanText = state.results[AnalysisType.DEEP_DIVE];
    if (!mealPlanText) {
      logger.warn('generateImage called but no meal plan text available.');
      return;
    }
    dispatch({ type: 'FETCH_START', payload: { analysisType: AnalysisType.GENERATE_IMAGE } });
    try {
      const data = await service.generateImageFromText(mealPlanText);
      dispatch({ type: 'FETCH_SUCCESS_IMAGE', payload: { data } });
    } catch (err: unknown) {
      logger.error('generateImage failed', { error: err });
      const message =
        err instanceof Error
          ? err.message
          : 'An unexpected error occurred during image generation.';
      dispatch({ type: 'FETCH_ERROR', payload: { error: message } });
    }
  }, [service, state.results]);
 
  const clearError = useCallback(() => {
    dispatch({ type: 'CLEAR_ERROR' });
  }, []);
 
  const resetAnalysis = useCallback(() => {
    dispatch({ type: 'RESET_STATE' });
  }, []);
 
  return useMemo(
    () => ({
      ...state,
      runAnalysis,
      generateImage,
      clearError,
      resetAnalysis,
    }),
    [state, runAnalysis, generateImage, clearError, resetAnalysis],
  );
};