/**
 * useAgentMemory Hook
 * Manages agent memory state with API integration
 * OQI-007: LLM Strategy Agent - Memory Hook
 */

import { useState, useCallback, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../../../lib/apiClient';
import type { MemoryItem, MemoryStats, MemoryCategory } from '../components/MemoryManagerPanel';

// ============================================================================
// Types
// ============================================================================

interface UseAgentMemoryOptions {
  enabled?: boolean;
  autoRefresh?: boolean;
  refreshInterval?: number;
}

interface UseAgentMemoryReturn {
  memories: MemoryItem[];
  stats: MemoryStats;
  isLoading: boolean;
  isError: boolean;
  error: Error | null;
  addMemory: (memory: Omit<MemoryItem, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>;
  updateMemory: (id: string, updates: Partial<MemoryItem>) => Promise<void>;
  deleteMemory: (id: string) => Promise<void>;
  clearCategory: (category: MemoryCategory) => Promise<void>;
  refresh: () => Promise<void>;
  searchMemories: (query: string) => MemoryItem[];
}

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

const memoryApi = {
  getAll: async (): Promise<{ memories: MemoryItem[]; stats: MemoryStats }> => {
    const response = await apiClient.get('/llm/memory');
    return response.data;
  },

  add: async (memory: Omit<MemoryItem, 'id' | 'createdAt' | 'updatedAt'>): Promise<MemoryItem> => {
    const response = await apiClient.post('/llm/memory', memory);
    return response.data;
  },

  update: async (id: string, updates: Partial<MemoryItem>): Promise<MemoryItem> => {
    const response = await apiClient.patch(`/llm/memory/${id}`, updates);
    return response.data;
  },

  delete: async (id: string): Promise<void> => {
    await apiClient.delete(`/llm/memory/${id}`);
  },

  clearCategory: async (category: MemoryCategory): Promise<void> => {
    await apiClient.delete(`/llm/memory/category/${category}`);
  },
};

// ============================================================================
// Default Values
// ============================================================================

const DEFAULT_STATS: MemoryStats = {
  totalItems: 0,
  totalTokens: 0,
  maxTokens: 8000,
  byCategory: {
    preferences: 0,
    strategies: 0,
    history: 0,
    custom: 0,
  },
};

// ============================================================================
// Hook Implementation
// ============================================================================

export function useAgentMemory(options: UseAgentMemoryOptions = {}): UseAgentMemoryReturn {
  const { enabled = true, autoRefresh = false, refreshInterval = 60000 } = options;
  const queryClient = useQueryClient();

  // Query for memories
  const {
    data,
    isLoading,
    isError,
    error,
    refetch,
  } = useQuery({
    queryKey: ['agent-memory'],
    queryFn: memoryApi.getAll,
    enabled,
    refetchInterval: autoRefresh ? refreshInterval : false,
    staleTime: 30000, // 30 seconds
  });

  // Add mutation
  const addMutation = useMutation({
    mutationFn: memoryApi.add,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['agent-memory'] });
    },
  });

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: ({ id, updates }: { id: string; updates: Partial<MemoryItem> }) =>
      memoryApi.update(id, updates),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['agent-memory'] });
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: memoryApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['agent-memory'] });
    },
  });

  // Clear category mutation
  const clearCategoryMutation = useMutation({
    mutationFn: memoryApi.clearCategory,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['agent-memory'] });
    },
  });

  // Handlers
  const addMemory = useCallback(async (memory: Omit<MemoryItem, 'id' | 'createdAt' | 'updatedAt'>) => {
    await addMutation.mutateAsync(memory);
  }, [addMutation]);

  const updateMemory = useCallback(async (id: string, updates: Partial<MemoryItem>) => {
    await updateMutation.mutateAsync({ id, updates });
  }, [updateMutation]);

  const deleteMemory = useCallback(async (id: string) => {
    await deleteMutation.mutateAsync(id);
  }, [deleteMutation]);

  const clearCategory = useCallback(async (category: MemoryCategory) => {
    await clearCategoryMutation.mutateAsync(category);
  }, [clearCategoryMutation]);

  const refresh = useCallback(async () => {
    await refetch();
  }, [refetch]);

  const searchMemories = useCallback((query: string): MemoryItem[] => {
    if (!data?.memories || !query.trim()) return data?.memories || [];
    const lowerQuery = query.toLowerCase();
    return data.memories.filter(
      (m) => m.key.toLowerCase().includes(lowerQuery) || m.value.toLowerCase().includes(lowerQuery)
    );
  }, [data?.memories]);

  return {
    memories: data?.memories || [],
    stats: data?.stats || DEFAULT_STATS,
    isLoading,
    isError,
    error: error as Error | null,
    addMemory,
    updateMemory,
    deleteMemory,
    clearCategory,
    refresh,
    searchMemories,
  };
}

export default useAgentMemory;
