import api from '../../../shared/utils/api';

// ==================== DTOs ====================

export type ConversationStatus = 'ACTIVE' | 'ENDED' | 'ARCHIVED';

export interface DeviceInfo {
  ip?: string;
  userAgent?: string;
  fingerprint?: string;
  region?: string;
}

export interface TokenDetails {
  cacheCreationTokens: number;
  cacheReadTokens: number;
  totalTokens: number;
  estimatedCost: number;
  apiCallCount: number;
}

export interface ConversationDto {
  id: string;
  userId: string;
  status: ConversationStatus;
  title: string | null;
  summary: string | null;
  category: string | null;
  messageCount: number;
  userMessageCount: number;
  assistantMessageCount: number;
  totalInputTokens: number;
  totalOutputTokens: number;
  tokenDetails?: TokenDetails;
  rating: number | null;
  feedback: string | null;
  hasConverted: boolean;
  consultingStage: string | null;
  consultingState?: Record<string, unknown> | null;
  collectedInfo?: Record<string, unknown> | null;
  recommendedPrograms?: string[] | null;
  conversionPath?: string | null;
  deviceInfo: DeviceInfo | null;
  createdAt: string;
  updatedAt: string;
  endedAt: string | null;
}

export interface ConversationListItem {
  id: string;
  userId: string;
  status: ConversationStatus;
  title: string | null;
  messageCount: number;
  hasConverted: boolean;
  consultingStage: string | null;
  deviceInfo: DeviceInfo | null;
  createdAt: string;
  updatedAt: string;
  endedAt: string | null;
}

export interface MessageDto {
  id: string;
  conversationId: string;
  role: 'user' | 'assistant' | 'system';
  type: string;
  content: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
}

export interface PaginatedConversations {
  items: ConversationDto[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface GlobalTokenStats {
  totalInputTokens: number;
  totalOutputTokens: number;
  totalCacheCreationTokens: number;
  totalCacheReadTokens: number;
  totalTokens: number;
  totalEstimatedCost: number;
  totalApiCalls: number;
}

export interface TodayTokenStats {
  totalInputTokens: number;
  totalOutputTokens: number;
  totalTokens: number;
  totalEstimatedCost: number;
  totalApiCalls: number;
}

export interface ConversationStatistics {
  total: number;
  active: number;
  ended: number;
  converted: number;
  todayCount: number;
  conversionRate: string;
  tokenStats: GlobalTokenStats;
  todayTokenStats: TodayTokenStats;
}

export interface ConversationQueryParams {
  page?: number;
  pageSize?: number;
  status?: ConversationStatus;
  userId?: string;
  startDate?: string;
  endDate?: string;
  hasConverted?: boolean;
  sortBy?: 'createdAt' | 'updatedAt' | 'messageCount';
  sortOrder?: 'ASC' | 'DESC';
}

// ==================== Agent Analytics DTOs ====================

export interface AgentExecutionDto {
  id: string;
  conversationId: string;
  agentType: string;
  agentName: string;
  durationMs: number;
  success: boolean;
  errorMessage: string | null;
  toolCallsCount: number;
  createdAt: string;
}

export interface AgentStatisticsDto {
  agentType: string;
  agentName: string;
  totalCalls: number;
  successCount: number;
  failureCount: number;
  successRate: number;
  avgDurationMs: number;
  minDurationMs: number;
  maxDurationMs: number;
}

export interface AgentTrendDto {
  date: string;
  agentType: string;
  calls: number;
  avgDurationMs: number;
  successRate: number;
}

// ==================== API ====================

export const conversationsApi = {
  // List conversations with pagination
  listConversations: async (params: ConversationQueryParams): Promise<PaginatedConversations> => {
    const response = await api.get('/conversations/admin/list', { params });
    return response.data.data;
  },

  // Get conversations by user ID
  getConversationsByUser: async (userId: string, limit = 10): Promise<ConversationListItem[]> => {
    const response = await api.get(`/conversations/admin/by-user/${userId}`, {
      params: { limit },
    });
    return response.data.data;
  },

  // Get conversation detail
  getConversation: async (id: string): Promise<ConversationDto> => {
    const response = await api.get(`/conversations/admin/${id}`);
    return response.data.data;
  },

  // Get conversation messages
  getConversationMessages: async (id: string): Promise<MessageDto[]> => {
    const response = await api.get(`/conversations/admin/${id}/messages`);
    return response.data.data;
  },

  // Get statistics
  getStatistics: async (): Promise<ConversationStatistics> => {
    const response = await api.get('/conversations/admin/statistics/overview');
    return response.data.data;
  },

  // Get agent executions for a conversation
  getConversationAgentExecutions: async (id: string): Promise<AgentExecutionDto[]> => {
    const response = await api.get(`/conversations/admin/${id}/agent-executions`);
    return response.data.data;
  },

  // Get agent statistics (aggregated)
  getAgentStatistics: async (days = 30): Promise<AgentStatisticsDto[]> => {
    const response = await api.get('/conversations/admin/statistics/agents', {
      params: { days: days.toString() },
    });
    return response.data.data;
  },

  // Get agent usage trend
  getAgentTrend: async (days = 7, agentType?: string): Promise<AgentTrendDto[]> => {
    const response = await api.get('/conversations/admin/statistics/agents/trend', {
      params: { days: days.toString(), agentType },
    });
    return response.data.data;
  },
};
