/**
 * Twilio WhatsApp AI Agent - Type Definitions
 */

// ─── Twilio Types ────────────────────────────────────────

export interface TwilioWhatsAppCredentials {
  accountSid: string;
  authToken: string;
  whatsappNumber: string; // e.g., "+14155238886"
}

export interface TwilioSendResult {
  success: boolean;
  messageSid?: string;
  error?: string;
}

export interface TwilioIncomingMessage {
  messageSid: string;
  from: string;           // "whatsapp:+966501234567"
  to: string;             // "whatsapp:+14155238886"
  body: string;
  numMedia: number;
  mediaUrls: string[];
  mediaContentTypes: string[];
  profileName?: string;
}

// ─── OpenRouter Types ────────────────────────────────────

export interface OpenRouterConfig {
  apiKey: string;
  model: string;           // e.g., "anthropic/claude-sonnet-4"
  maxTokens: number;
  temperature: number;
}

export interface ChatMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

export interface OpenRouterResponse {
  success: boolean;
  content: string;
  model: string;
  usage: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
  error?: string;
}

// ─── AI Engine Types ─────────────────────────────────────

export type AIIntent =
  | 'company_query'
  | 'booking_request'
  | 'amend_appointment'
  | 'check_status'
  | 'greeting'
  | 'general'
  | 'off_topic'
  | 'abuse'
  | 'property_search'
  | 'viewing_request'
  | 'viewing_management'
  | 'quotation_request'
  | 'review_request';

export type AIActionType =
  | 'search_kb'
  | 'create_booking'
  | 'reschedule'
  | 'cancel'
  | 'generate_payment_link'
  | 'check_status'
  | 'none'
  | 'search_properties'
  | 'book_viewing'
  | 'check_availability'
  | 'reschedule_viewing'
  | 'cancel_viewing'
  | 'request_quotation'
  | 'request_review'
  | 'send_post_booking_action';

export interface StructuredAIResponse {
  intent: AIIntent;
  response: string;
  language: 'en' | 'ar';
  action?: {
    type: AIActionType;
    params?: Record<string, unknown>;
  };
  collectedInfo?: {
    name?: string;
    email?: string;
    phone?: string;
    service?: string;
    date?: string;      // YYYY-MM-DD
    time?: string;      // HH:MM
    depositChoice?: boolean;
    categorySelection?: number;
    serviceSelection?: number;
    // Real estate fields
    propertyQuery?: string;
    bedrooms?: number;
    maxBudget?: number;
    district?: string;
    propertyType?: string;
    listingType?: string;
    propertyId?: string;
    viewingId?: string;
    // Sector-specific fields
    sectorFields?: Record<string, unknown>;
  };
  missingFields?: string[];
  guardrailTriggered?: boolean;
  guardrailReason?: string;
}

// ─── Conversation Types ──────────────────────────────────

export interface ConversationContext {
  organizationId: string;
  organizationName: string;
  customerPhone: string;
  customerName?: string;
  customerEmail?: string;
  language: 'en' | 'ar';
  conversationHistory: Array<{
    role: 'user' | 'assistant';
    content: string;
    timestamp: Date;
  }>;
  conversationState: BookingFlowState | null;
  isReturningCustomer: boolean;
  industry?: string;
  sector?: string;
}

export type BookingFlowState =
  | { phase: 'selecting_language' }
  | { phase: 'idle' }
  | { phase: 'browsing_categories' }
  | { phase: 'browsing_services'; category: string }
  | { phase: 'collecting_info'; collected: Partial<BookingInfo>; missing: string[] }
  | { phase: 'awaiting_deposit_choice'; bookingInfo: BookingInfo }
  | { phase: 'awaiting_payment'; bookingId: string; paymentUrl: string }
  | { phase: 'completed'; bookingId: string }
  // Amend / cancel appointment flow
  | { phase: 'selecting_booking_for_amend'; candidateIds: string[]; action: 'reschedule' | 'cancel' }
  | { phase: 'amending_appointment'; bookingId: string; newDate?: string; newTime?: string }
  | { phase: 'awaiting_cancel_confirmation'; bookingId: string }
  // Real estate phases
  | { phase: 're_searching' }
  | { phase: 're_viewing_results'; propertyIds: string[] }
  | { phase: 're_collecting_viewing_info'; propertyId: string; collected: Partial<REViewingInfo>; missing: string[] }
  | { phase: 're_viewing_booked'; viewingId: string; propertyId: string };

export interface BookingInfo {
  name: string;
  email?: string;
  phone: string;
  service: string;
  date: string;      // YYYY-MM-DD
  time: string;      // HH:MM
  duration: number;
  depositRequired: boolean;
  depositAmount?: number;
  sectorMetadata?: Record<string, unknown>;
}

export interface REViewingInfo {
  name: string;
  phone: string;
  email?: string;
  propertyId: string;
  date: string;      // YYYY-MM-DD
  time: string;      // HH:MM
}

// ─── Engine Result ───────────────────────────────────────

export interface EngineResult {
  responseText: string;
  intent: AIIntent;
  action?: AIActionType;
  newState: BookingFlowState | null;
  paymentUrl?: string;
  bookingId?: string;
  // ── Conversation learning metadata (Phase 5) ──
  kbUsed?: boolean;        // Was the KB queried for this response?
  kbConfidence?: number;   // Match quality 0-1 (0 if not used)
  escalatedToHuman?: boolean;
}

// ─── Guardrails ──────────────────────────────────────────

export type GuardrailViolationType =
  | 'prompt_injection'
  | 'off_topic'
  | 'abuse'
  | 'pii_leak'
  | 'too_long'
  | 'xss';

export interface GuardrailResult {
  safe: boolean;
  reason?: string;
  type?: GuardrailViolationType;
  sanitizedMessage: string;
}
