/**
 * RAG (Retrieval-Augmented Generation) Module Types
 *
 * Type definitions for the Legal RAG System:
 * - 21 pre-indexed legal documents
 * - Semantic search with Qdrant
 * - LLM-powered legal assistant
 * - Customer document upload
 */

import type { RegulationCode } from './compliance'

// =============================================================================
// LEGAL CORPUS
// =============================================================================

export interface RagLegalDocument {
  id: string
  code: RegulationCode | string
  name: string
  fullName: string
  jurisdiction: 'EU' | 'DE' | 'INT'
  language: 'de' | 'en'
  effectiveDate: Date
  sourceUrl?: string
  chunks: number
  lastIndexed: Date
}

export interface LegalChunk {
  id: string
  documentId: string
  documentCode: string
  chunkIndex: number
  content: string
  article?: string
  section?: string
  metadata: ChunkMetadata
  embedding?: number[]
}

export interface ChunkMetadata {
  articleNumber?: string
  sectionTitle?: string
  paragraph?: number
  keywords: string[]
  references: string[]
  effectiveDate?: Date
}

// Pre-indexed documents in the Legal Corpus
export const LEGAL_CORPUS_DOCUMENTS: readonly string[] = [
  'DSGVO',      // 99 Chunks
  'AI_ACT',     // 85 Chunks
  'NIS2',       // 46 Chunks
  'EPRIVACY',
  'TDDDG',
  'SCC',        // Standard Contractual Clauses
  'DPF',        // Data Privacy Framework
  'CRA',        // Cyber Resilience Act
  'EUCSA',      // EU Cybersecurity Act
  'DATA_ACT',
  'DGA',        // Data Governance Act
  'DSA',        // Digital Services Act
  'EAA',        // European Accessibility Act
  'BDSG',       // German BDSG
  'ISO_27001',
  'BSI_GRUNDSCHUTZ',
  'KRITIS',
  'BAIT',       // Banking IT requirements
  'VAIT',       // Insurance IT requirements
  'SOC2',
  'PCI_DSS',
] as const

// =============================================================================
// SEARCH & RETRIEVAL
// =============================================================================

export interface SearchQuery {
  query: string
  filters?: SearchFilters
  limit?: number
  offset?: number
  includeMetadata?: boolean
  scoreThreshold?: number
}

export interface SearchFilters {
  documentCodes?: string[]
  jurisdictions?: ('EU' | 'DE' | 'INT')[]
  languages?: ('de' | 'en')[]
  articles?: string[]
  dateFrom?: Date
  dateTo?: Date
}

export interface SearchResult {
  id: string
  documentCode: string
  documentName: string
  content: string
  article?: string
  section?: string
  score: number
  highlights: string[]
  metadata: ChunkMetadata
}

export interface SearchResponse {
  results: SearchResult[]
  total: number
  query: string
  processingTimeMs: number
  filters?: SearchFilters
}

// =============================================================================
// LEGAL ASSISTANT
// =============================================================================

export interface AssistantQuery {
  question: string
  context?: string
  documents?: string[]
  maxSources?: number
  language?: 'de' | 'en'
  responseFormat?: 'detailed' | 'concise' | 'bullet_points'
}

export interface AssistantResponse {
  answer: string
  sources: SourceReference[]
  confidence: number // 0-1
  processingTimeMs: number
  suggestedFollowUps?: string[]
}

export interface SourceReference {
  documentCode: string
  documentName: string
  article?: string
  content: string
  relevanceScore: number
  url?: string
}

// =============================================================================
// CUSTOMER DOCUMENTS
// =============================================================================

export type CustomerDocumentType =
  | 'POLICY'
  | 'GUIDELINE'
  | 'CONTRACT'
  | 'SLA'
  | 'PROCEDURE'
  | 'RISK_ASSESSMENT'
  | 'AUDIT_REPORT'
  | 'OTHER'

export type IndexingStatus =
  | 'PENDING'
  | 'PROCESSING'
  | 'INDEXED'
  | 'FAILED'
  | 'OUTDATED'

export interface CustomerDocument {
  id: string
  tenantId: string
  name: string
  fileName: string
  type: CustomerDocumentType
  mimeType: string
  fileSize: number
  uploadedBy: string
  uploadedAt: Date
  indexingStatus: IndexingStatus
  indexedAt?: Date
  chunkCount?: number
  error?: string
  tags: string[]
  metadata?: Record<string, unknown>
}

export interface DocumentUploadRequest {
  name: string
  type: CustomerDocumentType
  tags?: string[]
  metadata?: Record<string, unknown>
  file: File | Blob
}

export interface DocumentUploadResponse {
  id: string
  status: IndexingStatus
  message: string
  estimatedProcessingTimeMs?: number
}

// =============================================================================
// VECTOR DATABASE
// =============================================================================

export interface VectorDBConfig {
  provider: 'qdrant' | 'pinecone' | 'weaviate'
  url: string
  apiKey?: string
  collection: string
  embeddingModel: string
  embeddingDimensions: number
}

export interface EmbeddingRequest {
  texts: string[]
  model?: string
}

export interface EmbeddingResponse {
  embeddings: number[][]
  model: string
  usage: {
    promptTokens: number
    totalTokens: number
  }
}

// =============================================================================
// RAG PIPELINE
// =============================================================================

export interface RAGPipelineConfig {
  retriever: {
    topK: number
    scoreThreshold: number
    reranking: boolean
    hybridSearch: boolean
  }
  generator: {
    model: string
    temperature: number
    maxTokens: number
    systemPrompt?: string
  }
  postProcessing: {
    citationFormat: 'inline' | 'footnote' | 'none'
    sourceVerification: boolean
    hallucizationCheck: boolean
  }
}

export interface RAGContext {
  query: string
  retrievedChunks: LegalChunk[]
  rerankedChunks?: LegalChunk[]
  generatedResponse?: string
  citations: Citation[]
}

export interface Citation {
  id: string
  chunkId: string
  documentCode: string
  article?: string
  quotedText: string
  confidence: number
}

// =============================================================================
// CHAT HISTORY
// =============================================================================

export interface ChatMessage {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: Date
  sources?: SourceReference[]
  metadata?: Record<string, unknown>
}

export interface ChatSession {
  id: string
  tenantId: string
  userId: string
  messages: ChatMessage[]
  createdAt: Date
  updatedAt: Date
  title?: string
  tags?: string[]
}

// =============================================================================
// ANALYTICS
// =============================================================================

export interface RAGAnalytics {
  totalQueries: number
  averageResponseTimeMs: number
  topDocuments: Array<{ code: string; queryCount: number }>
  topQuestions: Array<{ question: string; count: number }>
  satisfactionScore?: number
  period: 'day' | 'week' | 'month'
}
