/**
 * Knowledge Base Types
 * Types for document management, RAG, and FAQ system
 */

export type KBDocumentStatus = 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';

export interface KnowledgeBaseDocument {
  id: string;
  userId: string;
  filename: string;
  originalName: string;
  mimeType: string;
  fileSize: number;
  storagePath: string;
  title: string | null;
  description: string | null;
  category: string;
  status: KBDocumentStatus;
  processedAt: Date | null;
  processingError: string | null;
  chunkCount: number;
  embeddingModel: string | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface KnowledgeBaseChunk {
  id: string;
  documentId: string;
  content: string;
  chunkIndex: number;
  embedding: number[] | null;
  metadata: Record<string, unknown> | null;
  createdAt: Date;
}

export interface KnowledgeBaseFAQ {
  id: string;
  userId: string;
  questionEn: string;
  questionAr: string | null;
  answerEn: string;
  answerAr: string | null;
  category: string;
  priority: number;
  isActive: boolean;
  embedding: number[] | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface KnowledgeBaseSettings {
  id: string;
  userId: string;
  isEnabled: boolean;
  onboardingCompleted: boolean;
  maxChunksPerQuery: number;
  similarityThreshold: number;
  welcomeMessage: string | null;
  customInstructions: string | null;
  createdAt: Date;
  updatedAt: Date;
}

// API Request/Response types
export interface UploadDocumentRequest {
  file: File;
  title?: string;
  description?: string;
  category?: string;
}

export interface UploadDocumentResponse {
  success: boolean;
  document?: KnowledgeBaseDocument;
  error?: string;
}

export interface CreateFAQRequest {
  questionEn: string;
  questionAr?: string;
  answerEn: string;
  answerAr?: string;
  category?: string;
  priority?: number;
}

export interface UpdateFAQRequest extends Partial<CreateFAQRequest> {
  isActive?: boolean;
}

export interface QueryKnowledgeBaseRequest {
  query: string;
  language?: 'en' | 'ar';
  maxResults?: number;
}

export interface QueryKnowledgeBaseResponse {
  success: boolean;
  answer?: string;
  sources?: {
    documentId: string;
    documentTitle: string;
    content: string;
    relevanceScore: number;
  }[];
  relatedFAQs?: {
    id: string;
    question: string;
    answer: string;
  }[];
  error?: string;
}

// Document categories
export const DOCUMENT_CATEGORIES = [
  { value: 'general', labelEn: 'General', labelAr: 'عام' },
  { value: 'services', labelEn: 'Services', labelAr: 'الخدمات' },
  { value: 'policies', labelEn: 'Policies', labelAr: 'السياسات' },
  { value: 'pricing', labelEn: 'Pricing', labelAr: 'التسعير' },
  { value: 'faq', labelEn: 'FAQ', labelAr: 'الأسئلة الشائعة' },
  { value: 'training', labelEn: 'Training Materials', labelAr: 'مواد التدريب' },
  { value: 'procedures', labelEn: 'Procedures', labelAr: 'الإجراءات' },
] as const;

export type DocumentCategory = typeof DOCUMENT_CATEGORIES[number]['value'];

// Allowed file types
export const ALLOWED_FILE_TYPES = [
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'text/plain',
  'text/markdown',
  'text/csv',
] as const;

export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

export const FILE_TYPE_LABELS: Record<string, string> = {
  'application/pdf': 'PDF',
  'application/msword': 'Word (DOC)',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word (DOCX)',
  'text/plain': 'Text',
  'text/markdown': 'Markdown',
  'text/csv': 'CSV',
};

// === MULTIMODAL EXTENSIONS ===

// Media types for multimodal KB
export type KBMediaType = 'document' | 'image' | 'video' | 'audio';

export const MEDIA_TYPE_LABELS: Record<KBMediaType, { en: string; ar: string }> = {
  document: { en: 'Document', ar: 'مستند' },
  image: { en: 'Image', ar: 'صورة' },
  video: { en: 'Video', ar: 'فيديو' },
  audio: { en: 'Audio', ar: 'صوت' },
};

// Extended allowed file types (multimodal)
export const ALLOWED_MEDIA_TYPES = [
  // Documents
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'text/plain',
  'text/markdown',
  'text/csv',
  // Images
  'image/png',
  'image/jpeg',
  'image/webp',
  // Videos
  'video/mp4',
  'video/quicktime',
  // Audio
  'audio/mpeg',
  'audio/wav',
  'audio/mp4',
  'audio/x-m4a',
] as const;

export const MAX_MEDIA_SIZE = 50 * 1024 * 1024; // 50MB for video/audio
export const MAX_VIDEO_DURATION_SECONDS = 120;

export const MEDIA_FILE_TYPE_LABELS: Record<string, string> = {
  ...FILE_TYPE_LABELS,
  'image/png': 'PNG Image',
  'image/jpeg': 'JPEG Image',
  'image/webp': 'WebP Image',
  'video/mp4': 'MP4 Video',
  'video/quicktime': 'MOV Video',
  'audio/mpeg': 'MP3 Audio',
  'audio/wav': 'WAV Audio',
  'audio/mp4': 'M4A Audio',
  'audio/x-m4a': 'M4A Audio',
};

// Helper to determine media type from MIME
export function getMediaType(mimeType: string): KBMediaType {
  if (mimeType.startsWith('image/')) return 'image';
  if (mimeType.startsWith('video/')) return 'video';
  if (mimeType.startsWith('audio/')) return 'audio';
  return 'document';
}

// RAG types (used by gemini-rag.service.ts and pinecone-multimodal.service.ts)
export interface RAGCitation {
  documentId: string;
  documentTitle: string;
  excerpt: string;
  relevanceScore?: number;
  mediaType?: KBMediaType;
  mediaUrl?: string;
}

export interface RAGQueryResponse {
  success: boolean;
  answer: string;
  citations: RAGCitation[];
  mediaResults?: {
    type: KBMediaType;
    url: string;
    title: string;
    description?: string;
    relevanceScore: number;
    thumbnailUrl?: string;
  }[];
  metadata: {
    queryTimeMs: number;
    model: string;
    totalMatches?: number;
  };
}

// Extended document interface for multimodal items
export interface KnowledgeBaseMediaItem extends KnowledgeBaseDocument {
  mediaType: KBMediaType;
  mediaUrl?: string;
  thumbnailUrl?: string;
  duration?: number;
  dimensions?: { width: number; height: number };
  embeddingId?: string;
  aiDescription?: string;
}
