/**
 * Core types for the health monitoring system
 */

// Import shared types from sailboat-types
import {
  common
} from '@sailboat-computer/sailboat-types';

// Define constants for string literal types
export const HealthStatus = {
  HEALTHY: 'health_healthy' as common.HealthStatus,
  DEGRADED: 'health_degraded' as common.HealthStatus,
  UNHEALTHY: 'health_unhealthy' as common.HealthStatus,
  CRITICAL: 'health_critical' as common.HealthStatus,
  UNKNOWN: 'health_unknown' as common.HealthStatus
};

export const OperationalContext = {
  SAILING: 'context_sailing' as common.OperationalContext,
  MOTORING: 'context_motoring' as common.OperationalContext,
  ANCHORED: 'context_anchored' as common.OperationalContext,
  DOCKED: 'context_docked' as common.OperationalContext,
  MAINTENANCE: 'context_maintenance' as common.OperationalContext,
  EMERGENCY: 'context_emergency' as common.OperationalContext
};

export const MarineSystemType = {
  NAVIGATION: 'system_navigation' as common.MarineSystemType,
  SAFETY: 'system_safety' as common.MarineSystemType,
  POWER: 'system_power' as common.MarineSystemType,
  COMMUNICATION: 'system_communication' as common.MarineSystemType,
  PROPULSION: 'system_propulsion' as common.MarineSystemType,
  COMFORT: 'system_comfort' as common.MarineSystemType,
  MAINTENANCE: 'system_maintenance' as common.MarineSystemType,
  ENVIRONMENTAL: 'system_environmental' as common.MarineSystemType
};

// Type aliases for enum types
export type HealthStatusType = common.HealthStatus;
export type OperationalContextType = common.OperationalContext;
export type MarineSystemTypeType = common.MarineSystemType;

// MarineEnvironmentStatus doesn't seem to exist in the common namespace
// Define it here for now as an interface instead of an enum
export interface MarineEnvironmentStatus {
  // Basic environment status
  status?: 'normal' | 'adverse' | 'severe';
  
  // Marine-specific properties
  seaState?: string;
  weather?: string;
  powerStatus?: string;
  criticalOperationsOnly?: boolean;
  
  // Additional properties can be added as needed
  [key: string]: any;
}

/**
 * Health check types
 */
export enum HealthCheckType {
  SENSOR = 'sensor',
  SERVICE = 'service',
  SYSTEM = 'system',
  NETWORK = 'network',
  POWER = 'power',
  STORAGE = 'storage',
  ENVIRONMENTAL = 'environmental'
}

/**
 * Individual health check result
 */
export interface HealthCheckResult {
  checkId: string;
  name: string;
  type: HealthCheckType;
  marineSystemType: MarineSystemTypeType;
  status: HealthStatusType;
  score: number;                    // 0-1 health score
  message: string;
  details?: Record<string, any>;
  timestamp: Date;
  executionTime: number;            // ms
  
  // Marine-specific data
  marineContext: {
    operationalContext: OperationalContextType;
    environmentalImpact: boolean;
    safetyImpact: boolean;
    powerImpact: number;            // Watts
  };
  
  // Thresholds and limits
  thresholds?: {
    warning: number;
    critical: number;
    unit?: string;
  };
  
  // Trend data
  trend?: {
    direction: 'improving' | 'stable' | 'degrading';
    rate: number;                   // Rate of change
    confidence: number;             // 0-1 confidence in trend
  };
}

/**
 * Aggregated health status for a system or component
 */
export interface SystemHealthStatus {
  systemId: string;
  name: string;
  marineSystemType: MarineSystemTypeType;
  overallStatus: HealthStatusType;
  overallScore: number;             // 0-1 aggregated health score
  
  // Component health checks
  healthChecks: HealthCheckResult[];
  
  // System metrics
  metrics: {
    totalChecks: number;
    healthyChecks: number;
    warningChecks: number;
    criticalChecks: number;
    offlineChecks: number;
    averageScore: number;
    lastUpdateTime: Date;
  };
  
  // Marine-specific system data
  marineData: {
    operationalDependency: 'essential' | 'important' | 'optional';
    powerConsumption: number;       // Current power usage in Watts
    environmentalSensitivity: number; // 0-1 how sensitive to marine environment
    maintenanceStatus: 'current' | 'due' | 'overdue';
    lastMaintenanceDate?: Date;
    nextMaintenanceDate?: Date;
  };
  
  // Recommendations
  recommendations: {
    immediate: string[];            // Immediate actions needed
    scheduled: string[];            // Scheduled maintenance items
    monitoring: string[];           // Items to monitor closely
  };
}

/**
 * Overall system health dashboard
 */
export interface SystemHealthDashboard {
  timestamp: Date;
  overallSystemHealth: {
    status: HealthStatusType;
    score: number;                  // 0-1 overall system health
    trend: 'improving' | 'stable' | 'degrading';
  };
  
  // System breakdowns
  systemStatuses: SystemHealthStatus[];
  
  // Marine environment impact
  marineEnvironment: MarineEnvironmentStatus;
  environmentalImpact: {
    affectedSystems: string[];
    severityLevel: 'low' | 'medium' | 'high';
    adaptationsActive: string[];
  };
  
  // Critical alerts
  criticalAlerts: {
    id: string;
    systemId: string;
    message: string;
    severity: 'warning' | 'critical';
    timestamp: Date;
    acknowledged: boolean;
  }[];
  
  // Performance metrics
  performanceMetrics: {
    totalHealthChecks: number;
    healthCheckExecutionTime: number; // Average ms
    systemResponseTime: number;     // Average system response time
    dataFreshness: number;          // Average age of health data in seconds
  };
  
  // Power and resource status
  resourceStatus: {
    powerConsumption: {
      current: number;              // Watts
      average: number;              // Average over time
      peak: number;                 // Peak consumption
      efficiency: number;           // 0-1 efficiency score
    };
    
    storageHealth: {
      diskUsage: number;            // 0-1 percentage
      diskHealth: HealthStatusType;
      dataIntegrity: number;        // 0-1 integrity score
    };
    
    networkHealth: {
      connectivity: HealthStatusType;
      latency: number;              // ms
      throughput: number;           // Mbps
      reliability: number;          // 0-1 reliability score
    };
  };
}

/**
 * Health check configuration
 */
export interface HealthCheckConfig {
  checkId: string;
  name: string;
  type: HealthCheckType;
  marineSystemType: MarineSystemTypeType;
  
  // Execution settings
  interval: number;                 // Check interval in ms
  timeout: number;                  // Check timeout in ms
  retryCount: number;               // Number of retries on failure
  
  // Thresholds
  thresholds: {
    warning: number;
    critical: number;
    unit?: string;
  };
  
  // Marine-specific settings
  marineSettings: {
    operationalContexts: OperationalContextType[]; // When to run this check
    environmentalSensitivity: number; // 0-1 sensitivity to marine conditions
    powerAware: boolean;            // Should consider power status
    safetyImpact: boolean;          // Does this affect vessel safety
  };
  
  // Advanced settings
  advanced: {
    trendAnalysis: boolean;         // Enable trend analysis
    predictiveAlerts: boolean;      // Enable predictive alerting
    adaptiveThresholds: boolean;    // Adjust thresholds based on conditions
    historicalComparison: boolean;  // Compare with historical data
  };
}

/**
 * Health monitoring event
 */
export interface HealthMonitoringEvent {
  eventId: string;
  timestamp: Date;
  eventType: 'health_check_completed' | 'status_changed' | 'alert_triggered' | 'system_recovery' | 'maintenance_due';
  
  // Event details
  systemId: string;
  checkId?: string;
  previousStatus?: HealthStatusType;
  currentStatus: HealthStatusType;
  
  // Event data
  data: {
    score?: number;
    message: string;
    details?: Record<string, any>;
    marineContext: {
      operationalContext: OperationalContextType;
      environmentalConditions: Record<string, any>;
      safetyImpact: boolean;
    };
  };
  
  // Alert information
  alert?: {
    severity: 'info' | 'warning' | 'critical';
    requiresAction: boolean;
    recommendedActions: string[];
    autoResolution: boolean;
  };
}

/**
 * Health trend data
 */
export interface HealthTrend {
  systemId: string;
  checkId: string;
  timeRange: {
    start: Date;
    end: Date;
    intervalMs: number;
  };
  
  // Trend data points
  dataPoints: {
    timestamp: Date;
    score: number;
    status: HealthStatusType;
    value?: number;
    marineConditions?: {
      seaState: string;
      weather: string;
      operationalContext: OperationalContextType;
    };
  }[];
  
  // Trend analysis
  analysis: {
    direction: 'improving' | 'stable' | 'degrading';
    rate: number;                   // Rate of change per hour
    confidence: number;             // 0-1 confidence in analysis
    seasonality: boolean;           // Is there seasonal pattern
    correlations: {                 // Correlations with other factors
      environmental: number;        // -1 to 1 correlation with environment
      operational: number;          // -1 to 1 correlation with operations
      maintenance: number;          // -1 to 1 correlation with maintenance
    };
  };
  
  // Predictions
  predictions: {
    nextWarning?: Date;             // Predicted next warning
    nextCritical?: Date;            // Predicted next critical status
    maintenanceRecommendation?: Date; // Recommended maintenance date
    confidence: number;             // 0-1 confidence in predictions
  };
}

/**
 * Marine-specific health metrics
 */
export interface MarineHealthMetrics {
  // Sensor health
  sensorHealth: {
    gps: HealthCheckResult;
    compass: HealthCheckResult;
    windSensor: HealthCheckResult;
    depthSounder: HealthCheckResult;
    speedLog: HealthCheckResult;
    ais: HealthCheckResult;
  };
  
  // Power system health
  powerHealth: {
    batteryVoltage: HealthCheckResult;
    chargingSystem: HealthCheckResult;
    powerConsumption: HealthCheckResult;
    solarPanels?: HealthCheckResult;
    windGenerator?: HealthCheckResult;
    shorepower?: HealthCheckResult;
  };
  
  // Communication health
  communicationHealth: {
    vhfRadio: HealthCheckResult;
    satelliteComm?: HealthCheckResult;
    cellularModem?: HealthCheckResult;
    wifi: HealthCheckResult;
  };
  
  // Safety system health
  safetyHealth: {
    anchorAlarm: HealthCheckResult;
    collisionAvoidance: HealthCheckResult;
    emergencyBeacon?: HealthCheckResult;
    fireDetection?: HealthCheckResult;
    bilgePump?: HealthCheckResult;
  };
  
  // Environmental monitoring
  environmentalHealth: {
    temperature: HealthCheckResult;
    humidity: HealthCheckResult;
    barometricPressure: HealthCheckResult;
    waterTemperature?: HealthCheckResult;
  };
}

/**
 * Health monitoring configuration
 */
export interface HealthMonitoringConfig {
  // Global settings
  globalSettings: {
    defaultCheckInterval: number;   // Default check interval in ms
    defaultTimeout: number;         // Default timeout in ms
    maxConcurrentChecks: number;    // Max concurrent health checks
    dataRetentionDays: number;      // How long to keep health data
  };
  
  // Marine-specific settings
  marineSettings: {
    environmentalAdaptation: boolean; // Adapt checks to marine conditions
    powerAwareChecking: boolean;    // Reduce checks when power is low
    operationalContextAware: boolean; // Adjust checks based on operational context
    predictiveMaintenance: boolean; // Enable predictive maintenance alerts
  };
  
  // Alert settings
  alertSettings: {
    enableEmailAlerts: boolean;
    enableSmsAlerts: boolean;
    enableAudioAlerts: boolean;
    alertThrottling: number;        // Min time between similar alerts (ms)
    escalationTimeout: number;      // Time before escalating unacknowledged alerts (ms)
  };
  
  // Dashboard settings
  dashboardSettings: {
    refreshInterval: number;        // Dashboard refresh interval in ms
    historicalDataRange: number;    // Days of historical data to show
    trendAnalysisEnabled: boolean;
    predictiveAlertsEnabled: boolean;
  };
}
