/**
 * Unified Event Type System - Single Source of Truth
 *
 * Complete rewrite matching backend response structure exactly.
 * NO backward compatibility, NO legacy fields.
 *
 * Backend files this mirrors:
 * - /services/alert_processor/app/models/events_clean.py
 * - /services/alert_processor/app/models/response_models_clean.py
 */

// ============================================================
// ENUMS - Matching Backend Exactly
// ============================================================

export enum EventClass {
  ALERT = 'alert',
  NOTIFICATION = 'notification',
  RECOMMENDATION = 'recommendation',
}

export enum AlertTypeClass {
  ACTION_NEEDED = 'action_needed',
  PREVENTED_ISSUE = 'prevented_issue',
  TREND_WARNING = 'trend_warning',
  ESCALATION = 'escalation',
  INFORMATION = 'information',
}

export enum PriorityLevel {
  CRITICAL = 'critical',    // 90-100
  IMPORTANT = 'important',  // 70-89
  STANDARD = 'standard',    // 50-69
  INFO = 'info',            // 0-49
}

export enum AlertStatus {
  ACTIVE = 'active',
  RESOLVED = 'resolved',
  ACKNOWLEDGED = 'acknowledged',
  IN_PROGRESS = 'in_progress',
  DISMISSED = 'dismissed',
}

export enum SmartActionType {
  APPROVE_PO = 'approve_po',
  REJECT_PO = 'reject_po',
  MODIFY_PO = 'modify_po',
  VIEW_PO_DETAILS = 'view_po_details',
  CALL_SUPPLIER = 'call_supplier',
  NAVIGATE = 'navigate',
  ADJUST_PRODUCTION = 'adjust_production',
  START_PRODUCTION_BATCH = 'start_production_batch',
  NOTIFY_CUSTOMER = 'notify_customer',
  CANCEL_AUTO_ACTION = 'cancel_auto_action',
  MARK_DELIVERY_RECEIVED = 'mark_delivery_received',
  COMPLETE_STOCK_RECEIPT = 'complete_stock_receipt',
  OPEN_REASONING = 'open_reasoning',
  SNOOZE = 'snooze',
  DISMISS = 'dismiss',
  MARK_READ = 'mark_read',
}

export enum NotificationType {
  STATE_CHANGE = 'state_change',
  COMPLETION = 'completion',
  ARRIVAL = 'arrival',
  DEPARTURE = 'departure',
  UPDATE = 'update',
  SYSTEM_EVENT = 'system_event',
}

export enum RecommendationType {
  OPTIMIZATION = 'optimization',
  COST_REDUCTION = 'cost_reduction',
  RISK_MITIGATION = 'risk_mitigation',
  TREND_INSIGHT = 'trend_insight',
  BEST_PRACTICE = 'best_practice',
}

// ============================================================
// CONTEXT INTERFACES - Matching Backend Response Models
// ============================================================

/**
 * i18n display context with parameterized content
 * Backend field name: "i18n" (NOT "display")
 */
export interface I18nDisplayContext {
  title_key: string;
  message_key: string;
  title_params: Record<string, any>;
  message_params: Record<string, any>;
}

export interface BusinessImpactContext {
  financial_impact_eur?: number;
  waste_prevented_eur?: number;
  time_saved_minutes?: number;
  production_loss_avoided_eur?: number;
  potential_loss_eur?: number;
}

/**
 * Urgency context
 * Backend field name: "urgency" (NOT "urgency_context")
 */
export interface UrgencyContext {
  deadline_utc?: string; // ISO date string
  hours_until_consequence?: number;
  auto_action_countdown_seconds?: number;
  auto_action_cancelled?: boolean;
  urgency_reason_key?: string; // i18n key
  urgency_reason_params?: Record<string, any>;
  priority: string; // "critical", "urgent", "normal", "info"
}

export interface UserAgencyContext {
  action_required: boolean;
  external_party_required?: boolean;
  external_party_name?: string;
  external_party_contact?: string;
  estimated_resolution_time_minutes?: number;
  user_control_level: string; // "full", "partial", "none"
  action_urgency: string; // "immediate", "soon", "normal"
}

export interface TrendContext {
  metric_name: string;
  current_value: number;
  baseline_value: number;
  change_percentage: number;
  direction: 'increasing' | 'decreasing';
  significance: 'high' | 'medium' | 'low';
  period_days: number;
  possible_causes?: string[];
}

/**
 * Smart action with parameterized i18n labels
 * Backend field name in Alert: "smart_actions" (NOT "actions")
 */
export interface SmartAction {
  action_type: string;
  label_key: string; // i18n key for button text
  label_params?: Record<string, any>;
  variant: 'primary' | 'secondary' | 'danger' | 'ghost';
  disabled: boolean;
  consequence_key?: string; // i18n key for consequence text
  consequence_params?: Record<string, any>;
  disabled_reason?: string;
  disabled_reason_key?: string; // i18n key for disabled reason
  disabled_reason_params?: Record<string, any>;
  estimated_time_minutes?: number;
  metadata: Record<string, any>;
}

export interface AIReasoningContext {
  summary_key?: string; // i18n key
  summary_params?: Record<string, any>;
  details?: Record<string, any>;
}

// ============================================================
// EVENT RESPONSE TYPES - Base and Specific Types
// ============================================================

/**
 * Base Event interface with common fields
 */
export interface Event {
  // Core Identity
  id: string;
  tenant_id: string;
  event_class: EventClass;
  event_domain: string;
  event_type: string;
  service: string;

  // i18n Display Context
  // CRITICAL: Backend uses "i18n", NOT "display"
  i18n: I18nDisplayContext;

  // Classification
  priority_level: PriorityLevel;
  status: string;

  // Timestamps
  created_at: string; // ISO date string
  updated_at: string; // ISO date string

  // Optional context fields
  event_metadata?: Record<string, any>;
}

/**
 * Alert - Full enrichment, lifecycle tracking
 */
export interface Alert extends Event {
  event_class: EventClass.ALERT;
  status: AlertStatus | string;

  // Alert-specific classification
  type_class: AlertTypeClass;
  priority_score: number; // 0-100

  // Rich Context
  // CRITICAL: Backend uses "urgency", NOT "urgency_context"
  business_impact?: BusinessImpactContext;
  urgency?: UrgencyContext;
  user_agency?: UserAgencyContext;
  trend_context?: TrendContext;
  orchestrator_context?: Record<string, any>;

  // AI Intelligence
  ai_reasoning?: AIReasoningContext;
  confidence_score: number;

  // Actions
  // CRITICAL: Backend uses "smart_actions", NOT "actions"
  smart_actions: SmartAction[];

  // Entity References
  // CRITICAL: Backend uses "entity_links", NOT "entity_refs"
  entity_links: Record<string, string>;

  // Timing Intelligence
  timing_decision?: string;
  scheduled_send_time?: string; // ISO date string

  // Placement
  placement_hints?: string[];

  // Escalation & Chaining
  action_created_at?: string; // ISO date string
  superseded_by_action_id?: string;
  hidden_from_ui?: boolean;

  // Lifecycle
  resolved_at?: string; // ISO date string
  acknowledged_at?: string; // ISO date string
  acknowledged_by?: string;
  resolved_by?: string;
  notes?: string;
  assigned_to?: string;
}

/**
 * Notification - Lightweight, ephemeral (7-day TTL)
 */
export interface Notification extends Event {
  event_class: EventClass.NOTIFICATION;

  // Notification-specific
  notification_type: NotificationType;

  // Entity Context (lightweight)
  entity_type?: string; // 'batch', 'delivery', 'po', etc.
  entity_id?: string;
  old_state?: string;
  new_state?: string;

  // Placement
  placement_hints?: string[];

  // TTL
  expires_at?: string; // ISO date string
}

/**
 * Recommendation - Medium weight, dismissible
 */
export interface Recommendation extends Event {
  event_class: EventClass.RECOMMENDATION;

  // Recommendation-specific
  recommendation_type: RecommendationType;

  // Context (lighter than alerts)
  estimated_impact?: Record<string, any>;
  suggested_actions?: SmartAction[];

  // AI Intelligence
  ai_reasoning?: AIReasoningContext;
  confidence_score?: number;

  // Dismissal
  dismissed_at?: string; // ISO date string
  dismissed_by?: string;
}

/**
 * Union type for all event responses
 */
export type EventResponse = Alert | Notification | Recommendation;

// ============================================================
// API RESPONSE WRAPPERS
// ============================================================

export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  limit: number;
  offset: number;
  has_next: boolean;
  has_previous: boolean;
}

export interface EventsSummary {
  total_count: number;
  active_count: number;
  critical_count: number;
  high_count: number;
  medium_count: number;
  low_count: number;
  resolved_count: number;
  acknowledged_count: number;
}

export interface EventQueryParams {
  priority_level?: PriorityLevel | string;
  status?: AlertStatus | string;
  resolved?: boolean;
  event_class?: EventClass | string;
  event_domain?: string;
  limit?: number;
  offset?: number;
}

// ============================================================
// TYPE GUARDS
// ============================================================

export function isAlert(event: EventResponse | Event): event is Alert {
  return event.event_class === EventClass.ALERT || event.event_class === 'alert';
}

export function isNotification(event: EventResponse | Event): event is Notification {
  return event.event_class === EventClass.NOTIFICATION || event.event_class === 'notification';
}

export function isRecommendation(event: EventResponse | Event): event is Recommendation {
  return event.event_class === EventClass.RECOMMENDATION || event.event_class === 'recommendation';
}

// ============================================================
// HELPER FUNCTIONS
// ============================================================

export function getPriorityColor(level: PriorityLevel | string): string {
  const levelValue = String(level);

  if (levelValue === PriorityLevel.CRITICAL || levelValue === 'critical') {
    return 'var(--color-error)';
  } else if (levelValue === PriorityLevel.IMPORTANT || levelValue === 'important') {
    return 'var(--color-warning)';
  } else if (levelValue === PriorityLevel.STANDARD || levelValue === 'standard') {
    return 'var(--color-info)';
  } else if (levelValue === PriorityLevel.INFO || levelValue === 'info') {
    return 'var(--color-success)';
  } else {
    return 'var(--color-info)';
  }
}

export function getPriorityIcon(level: PriorityLevel | string): string {
  const levelValue = String(level);

  if (levelValue === PriorityLevel.CRITICAL || levelValue === 'critical') {
    return 'alert-triangle';
  } else if (levelValue === PriorityLevel.IMPORTANT || levelValue === 'important') {
    return 'alert-circle';
  } else if (levelValue === PriorityLevel.STANDARD || levelValue === 'standard') {
    return 'info';
  } else if (levelValue === PriorityLevel.INFO || levelValue === 'info') {
    return 'check-circle';
  } else {
    return 'info';
  }
}

export function getTypeClassBadgeVariant(
  typeClass: AlertTypeClass | string
): 'default' | 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info' | 'outline' {
  // Convert to string and compare with known values
  const typeValue = String(typeClass);

  if (typeValue === AlertTypeClass.ACTION_NEEDED || typeValue === 'action_needed') {
    return 'error';
  } else if (typeValue === AlertTypeClass.PREVENTED_ISSUE || typeValue === 'prevented_issue') {
    return 'success';
  } else if (typeValue === AlertTypeClass.TREND_WARNING || typeValue === 'trend_warning') {
    return 'warning';
  } else if (typeValue === AlertTypeClass.ESCALATION || typeValue === 'escalation') {
    return 'error';
  } else if (typeValue === AlertTypeClass.INFORMATION || typeValue === 'information') {
    return 'info';
  } else {
    return 'default';
  }
}

export function formatTimeUntilConsequence(hours?: number): string {
  if (!hours) return '';

  if (hours < 1) {
    return `${Math.round(hours * 60)} minutes`;
  } else if (hours < 24) {
    return `${Math.round(hours)} hours`;
  } else {
    return `${Math.round(hours / 24)} days`;
  }
}

/**
 * Convert legacy alert format to new Event format
 * This function provides backward compatibility for older alert structures
 */
export function convertLegacyAlert(legacyAlert: any): Event {
  // If it's already in the new format, return as-is
  if (legacyAlert.event_class && legacyAlert.event_class in EventClass) {
    return legacyAlert;
  }

  // Convert legacy format to new format
  const newAlert: Event = {
    id: legacyAlert.id || legacyAlert.alert_id || '',
    tenant_id: legacyAlert.tenant_id || '',
    event_class: EventClass.ALERT, // Default to alert
    event_domain: legacyAlert.event_domain || '',
    event_type: legacyAlert.event_type || legacyAlert.type || '',
    service: legacyAlert.service || 'unknown',
    i18n: legacyAlert.i18n || {
      title_key: legacyAlert.title_key || legacyAlert.title || '',
      message_key: legacyAlert.message_key || legacyAlert.message || '',
      title_params: legacyAlert.title_params || {},
      message_params: legacyAlert.message_params || {},
    },
    priority_level: legacyAlert.priority_level || PriorityLevel.STANDARD,
    status: legacyAlert.status || 'active',
    created_at: legacyAlert.created_at || new Date().toISOString(),
    updated_at: legacyAlert.updated_at || new Date().toISOString(),
    event_metadata: legacyAlert.event_metadata || legacyAlert.metadata || {},
  };

  return newAlert;
}
