/**
 * AI Lawyer Service Client
 * Handles communication with the AI Lawyer RAG API
 */

export interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  timestamp?: number;
  sources?: Source[];
}

export interface Source {
  title: string;
  source: string;
  excerpt: string;
  score: number;
}

export interface AILawyerResponse {
  success: boolean;
  message: string;
  sources?: Source[];
  documentsSearched?: number;
  relevantFound?: number;
  conversationId?: string;
  disclaimer?: string;
  error?: string;
}

export interface ServiceStatus {
  success: boolean;
  status: 'online' | 'offline';
  service: string;
  ragService?: {
    status: string;
    documents_count: number;
  };
  error?: string;
}

class AILawyerService {
  private baseUrl: string;
  private conversationHistory: ChatMessage[] = [];
  private conversationId: string | null = null;

  constructor() {
    this.baseUrl = '/api/ai-lawyer';
  }

  /**
   * Send a message to the AI Lawyer
   */
  async sendMessage(message: string, useRag: boolean = true): Promise<AILawyerResponse> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message,
          conversationId: this.conversationId,
          history: this.conversationHistory.slice(-10), // Last 10 messages for context
          useRag
        }),
      });

      const data: AILawyerResponse = await response.json();

      if (data.success) {
        // Update conversation history
        this.conversationHistory.push({
          role: 'user',
          content: message,
          timestamp: Date.now()
        });

        this.conversationHistory.push({
          role: 'assistant',
          content: data.message,
          timestamp: Date.now(),
          sources: data.sources
        });

        // Store conversation ID
        if (data.conversationId) {
          this.conversationId = data.conversationId;
        }
      }

      return data;

    } catch (error) {
      console.error('AI Lawyer Service Error:', error);
      return {
        success: false,
        message: 'Failed to connect to the AI Lawyer service. Please try again.',
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * Check service status
   */
  async getStatus(): Promise<ServiceStatus> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      return await response.json();

    } catch (error) {
      console.error('AI Lawyer Status Check Error:', error);
      return {
        success: false,
        status: 'offline',
        service: 'AI Lawyer Chat',
        error: error instanceof Error ? error.message : 'Connection failed'
      };
    }
  }

  /**
   * Get conversation history
   */
  getHistory(): ChatMessage[] {
    return [...this.conversationHistory];
  }

  /**
   * Clear conversation history and start fresh
   */
  clearHistory(): void {
    this.conversationHistory = [];
    this.conversationId = null;
  }

  /**
   * Get current conversation ID
   */
  getConversationId(): string | null {
    return this.conversationId;
  }
}

// Export singleton instance
export const aiLawyerService = new AILawyerService();

// Export class for custom instances
export default AILawyerService;
