import { create } from 'zustand';

export interface AIStepLog {
  stepNumber: number;
  stepName: string;
  functionName: string;
  status: 'pending' | 'success' | 'error';
  timestamp: Date;
  message?: string;
  error?: string;
  duration?: number; // milliseconds
}

export interface AIRequestLog {
  id: string;
  timestamp: Date;
  function: string; // e.g., 'autoClusterKeywords', 'autoGenerateIdeas', 'autoGenerateContent', 'autoGenerateImages'
  endpoint: string;
  request: {
    method: string;
    body?: any;
    params?: any;
  };
  response?: {
    status: number;
    data?: any;
    error?: string;
    errorType?: string; // e.g., 'DATABASE_ERROR', 'VALIDATION_ERROR', 'PERMISSION_ERROR'
  };
  status: 'pending' | 'success' | 'error';
  duration?: number; // milliseconds
  requestSteps: AIStepLog[]; // Request steps (INIT, PREP, SAVE, DONE)
  responseSteps: AIStepLog[]; // Response steps (AI_CALL, PARSE)
}

interface AIRequestLogsStore {
  logs: AIRequestLog[];
  addLog: (log: Omit<AIRequestLog, 'id' | 'timestamp' | 'requestSteps' | 'responseSteps'>) => string;
  updateLog: (logId: string, updates: Partial<AIRequestLog>) => void;
  addRequestStep: (logId: string, step: Omit<AIStepLog, 'timestamp'>) => void;
  addResponseStep: (logId: string, step: Omit<AIStepLog, 'timestamp'>) => void;
  clearLogs: () => void;
  maxLogs: number;
}

export const useAIRequestLogsStore = create<AIRequestLogsStore>((set, get) => ({
  logs: [],
  maxLogs: 20, // Keep last 20 logs
  
  addLog: (log) => {
    const newLog: AIRequestLog = {
      ...log,
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: new Date(),
      requestSteps: [],
      responseSteps: [],
    };
    
    set((state) => {
      const updatedLogs = [newLog, ...state.logs].slice(0, state.maxLogs);
      return { logs: updatedLogs };
    });
    
    // Return the log ID so callers can add steps
    return newLog.id;
  },
  
  updateLog: (logId, updates) => {
    set((state) => {
      const updatedLogs = state.logs.map((log) => {
        if (log.id === logId) {
          return { ...log, ...updates };
        }
        return log;
      });
      return { logs: updatedLogs };
    });
  },
  
  addRequestStep: (logId, step) => {
    set((state) => {
      const updatedLogs = state.logs.map((log) => {
        if (log.id === logId) {
          const stepWithTimestamp: AIStepLog = {
            ...step,
            timestamp: new Date(),
          };
          return {
            ...log,
            requestSteps: [...log.requestSteps, stepWithTimestamp],
          };
        }
        return log;
      });
      return { logs: updatedLogs };
    });
  },
  
  addResponseStep: (logId, step) => {
    set((state) => {
      const updatedLogs = state.logs.map((log) => {
        if (log.id === logId) {
          const stepWithTimestamp: AIStepLog = {
            ...step,
            timestamp: new Date(),
          };
          return {
            ...log,
            responseSteps: [...log.responseSteps, stepWithTimestamp],
          };
        }
        return log;
      });
      return { logs: updatedLogs };
    });
  },
  
  clearLogs: () => {
    set({ logs: [] });
  },
}));

