/**
 * RAG Module
 *
 * Legal RAG system for semantic search and AI-powered legal assistance
 */

import type {
  SearchQuery,
  SearchResponse,
  AssistantQuery,
  AssistantResponse,
  ChatMessage,
} from '@breakpilot/compliance-sdk-types'
import { ComplianceClient } from '../client'

export class RAGModule {
  private client: ComplianceClient
  private chatHistory: ChatMessage[] = []
  private sessionId: string | null = null

  constructor(client: ComplianceClient) {
    this.client = client
  }

  // ---------------------------------------------------------------------------
  // Search
  // ---------------------------------------------------------------------------

  async search(query: string, options?: Partial<SearchQuery>): Promise<SearchResponse> {
    const searchRequest: SearchQuery = {
      query,
      limit: options?.limit ?? 10,
      offset: options?.offset ?? 0,
      filters: options?.filters,
      includeMetadata: options?.includeMetadata ?? true,
      scoreThreshold: options?.scoreThreshold ?? 0.5,
    }

    const response = await this.client.searchRAG({
      query: searchRequest.query,
      filters: searchRequest.filters,
      limit: searchRequest.limit,
      offset: searchRequest.offset,
    })

    // The client returns RAGSearchResponse (api.ts shape); enrich it with
    // the originating query so the consumer-facing SearchResponse shape
    // from types/rag.ts is satisfied.
    return {
      ...response,
      query: searchRequest.query,
    } as unknown as SearchResponse
  }

  async searchByRegulation(regulation: string, query: string): Promise<SearchResponse> {
    return this.search(query, {
      filters: {
        documentCodes: [regulation],
      },
    })
  }

  async searchByArticle(regulation: string, article: string): Promise<SearchResponse> {
    return this.search(`${regulation} Artikel ${article}`, {
      filters: {
        documentCodes: [regulation],
        articles: [article],
      },
    })
  }

  // ---------------------------------------------------------------------------
  // Legal Assistant
  // ---------------------------------------------------------------------------

  async ask(question: string, options?: Partial<AssistantQuery>): Promise<AssistantResponse> {
    const request: AssistantQuery = {
      question,
      context: options?.context,
      documents: options?.documents,
      maxSources: options?.maxSources ?? 5,
      language: options?.language ?? 'de',
      responseFormat: options?.responseFormat ?? 'detailed',
    }

    const response = await this.client.askRAG({
      question: request.question,
      context: request.context,
      documents: request.documents,
      maxSources: request.maxSources,
      language: request.language,
    })

    // Add to chat history
    this.chatHistory.push({
      id: `user-${Date.now()}`,
      role: 'user',
      content: question,
      timestamp: new Date(),
    })

    this.chatHistory.push({
      id: `assistant-${Date.now()}`,
      role: 'assistant',
      content: response.answer,
      timestamp: new Date(),
      sources: response.sources,
    })

    return response
  }

  async askAboutRegulation(regulation: string, question: string): Promise<AssistantResponse> {
    return this.ask(question, {
      documents: [regulation],
      context: `Kontext: Frage bezieht sich auf ${regulation}`,
    })
  }

  async explainArticle(regulation: string, article: string): Promise<AssistantResponse> {
    return this.ask(`Erkläre ${regulation} Artikel ${article} einfach und verständlich.`, {
      documents: [regulation],
    })
  }

  async checkCompliance(
    regulation: string,
    scenario: string
  ): Promise<AssistantResponse> {
    return this.ask(
      `Prüfe folgendes Szenario auf Compliance mit ${regulation}: ${scenario}`,
      {
        documents: [regulation],
        responseFormat: 'detailed',
      }
    )
  }

  // ---------------------------------------------------------------------------
  // Chat Session
  // ---------------------------------------------------------------------------

  startNewSession(): void {
    this.sessionId = `session-${Date.now()}`
    this.chatHistory = []
  }

  getChatHistory(): ChatMessage[] {
    return [...this.chatHistory]
  }

  clearChatHistory(): void {
    this.chatHistory = []
  }

  getSessionId(): string | null {
    return this.sessionId
  }

  // ---------------------------------------------------------------------------
  // Document Info
  // ---------------------------------------------------------------------------

  getAvailableRegulations(): readonly string[] {
    return [
      'DSGVO',
      'AI_ACT',
      'NIS2',
      'EPRIVACY',
      'TDDDG',
      'SCC',
      'DPF',
      'CRA',
      'EUCSA',
      'DATA_ACT',
      'DGA',
      'DSA',
      'EAA',
      'BDSG',
      'ISO_27001',
      'BSI_GRUNDSCHUTZ',
      'KRITIS',
      'BAIT',
      'VAIT',
      'SOC2',
      'PCI_DSS',
    ] as const
  }

  // ---------------------------------------------------------------------------
  // Quick Actions
  // ---------------------------------------------------------------------------

  async getQuickAnswer(question: string): Promise<string> {
    const response = await this.ask(question, {
      responseFormat: 'concise',
      maxSources: 3,
    })
    return response.answer
  }

  async findRelevantArticles(topic: string): Promise<SearchResponse> {
    return this.search(topic, {
      limit: 5,
      scoreThreshold: 0.7,
    })
  }
}

export function createRAGModule(client: ComplianceClient): RAGModule {
  return new RAGModule(client)
}
