/**
 * TypeScript types for Training service
 * Mirrored from backend schemas: services/training/app/schemas/training.py
 *
 * Coverage:
 * - Training Job CRUD (start, status, results)
 * - Model Management (trained models, metrics)
 * - Data Validation (quality checks, recommendations)
 * - Real-time Progress (WebSocket updates)
 * - Bulk Training Operations
 */

// ================================================================
// ENUMS
// ================================================================

/**
 * Training job status enumeration
 * Backend: TrainingStatus enum in schemas/training.py (lines 14-20)
 */
export enum TrainingStatus {
  PENDING = 'pending',
  RUNNING = 'running',
  COMPLETED = 'completed',
  FAILED = 'failed',
  CANCELLED = 'cancelled'
}

// ================================================================
// REQUEST TYPES
// ================================================================

/**
 * Request schema for starting a training job
 * Backend: TrainingJobRequest in schemas/training.py (lines 23-27)
 */
export interface TrainingJobRequest {
  products?: string[] | null;  // Specific products to train (if null, trains all)
  start_date?: string | null;  // ISO datetime string - start date for training data
  end_date?: string | null;  // ISO datetime string - end date for training data
}

/**
 * Request schema for training a single product
 * Backend: SingleProductTrainingRequest in schemas/training.py (lines 30-39)
 */
export interface SingleProductTrainingRequest {
  start_date?: string | null;  // ISO datetime string
  end_date?: string | null;  // ISO datetime string

  // Prophet-specific parameters
  seasonality_mode?: string;  // Default: "additive"
  daily_seasonality?: boolean;  // Default: true
  weekly_seasonality?: boolean;  // Default: true
  yearly_seasonality?: boolean;  // Default: true
}

/**
 * Request schema for validating training data
 * Backend: DataValidationRequest in schemas/training.py (lines 150-161)
 */
export interface DataValidationRequest {
  products?: string[] | null;  // Specific products to validate (if null, validates all)
  min_data_points?: number;  // Default: 30, ge=10, le=1000
  start_date?: string | null;  // ISO datetime string
  end_date?: string | null;  // ISO datetime string
}

/**
 * Request schema for bulk training operations
 * Backend: BulkTrainingRequest in schemas/training.py (lines 317-322)
 */
export interface BulkTrainingRequest {
  tenant_ids: string[];
  config?: TrainingJobConfig;
  priority?: number;  // Default: 1, ge=1, le=10
  schedule_time?: string | null;  // ISO datetime string
}

// ================================================================
// RESPONSE TYPES
// ================================================================

/**
 * Schema for date range information
 * Backend: DateRangeInfo in schemas/training.py (lines 41-44)
 */
export interface DateRangeInfo {
  start: string;  // ISO format
  end: string;  // ISO format
}

/**
 * Schema for training data summary
 * Backend: DataSummary in schemas/training.py (lines 46-53)
 */
export interface DataSummary {
  sales_records: number;
  weather_records: number;
  traffic_records: number;
  date_range: DateRangeInfo;
  data_sources_used: string[];
  constraints_applied?: Record<string, string>;  // Default: {}
}

/**
 * Schema for individual product training results
 * Backend: ProductTrainingResult in schemas/training.py (lines 55-63)
 */
export interface ProductTrainingResult {
  inventory_product_id: string;
  status: string;
  model_id?: string | null;
  data_points: number;
  metrics?: Record<string, number> | null;  // MAE, MAPE, etc.
  training_time_seconds?: number | null;
  error_message?: string | null;
}

/**
 * Schema for overall training results
 * Backend: TrainingResults in schemas/training.py (lines 65-71)
 */
export interface TrainingResults {
  total_products: number;
  successful_trainings: number;
  failed_trainings: number;
  products: ProductTrainingResult[];
  overall_training_time_seconds: number;
}

/**
 * Enhanced response schema for training job with detailed results
 * Backend: TrainingJobResponse in schemas/training.py (lines 73-101)
 */
export interface TrainingJobResponse {
  job_id: string;
  tenant_id: string;
  status: TrainingStatus;

  // Required fields for basic response
  message: string;
  created_at: string;  // ISO datetime string
  estimated_duration_minutes: number;

  // Detailed fields (optional)
  training_results?: TrainingResults | null;
  data_summary?: DataSummary | null;
  completed_at?: string | null;  // ISO datetime string

  // Additional optional fields
  error_details?: Record<string, any> | null;
  processing_metadata?: Record<string, any> | null;
}

/**
 * Response schema for training job status checks
 * Backend: TrainingJobStatus in schemas/training.py (lines 103-124)
 */
export interface TrainingJobStatus {
  job_id: string;
  status: TrainingStatus;
  progress: number;  // 0-100
  current_step: string;
  started_at: string;  // ISO datetime string
  completed_at?: string | null;  // ISO datetime string
  products_total: number;
  products_completed: number;
  products_failed: number;
  error_message?: string | null;
  estimated_time_remaining_seconds?: number | null;  // Estimated time remaining in seconds
  estimated_completion_time?: string | null;  // ISO datetime string of estimated completion
  message?: string | null;  // Optional status message
}

/**
 * Schema for real-time training job progress updates
 * Backend: TrainingJobProgress in schemas/training.py (lines 127-147)
 */
export interface TrainingJobProgress {
  job_id: string;
  status: TrainingStatus;
  progress: number;  // 0-100, ge=0, le=100
  current_step: string;
  current_product?: string | null;
  products_completed: number;
  products_total: number;
  estimated_time_remaining_minutes?: number | null;
  estimated_time_remaining_seconds?: number | null;
  estimated_completion_time?: string | null;  // ISO datetime string of estimated completion
  timestamp: string;  // ISO datetime string
}

/**
 * Response schema for data validation results
 * Backend: DataValidationResponse in schemas/training.py (lines 164-173)
 */
export interface DataValidationResponse {
  is_valid: boolean;
  issues: string[];  // Default: []
  recommendations: string[];  // Default: []
  estimated_time_minutes: number;
  products_analyzed: number;
  total_data_points: number;
  products_with_insufficient_data: string[];  // Default: []
  data_quality_score: number;  // 0.0-1.0, ge=0.0, le=1.0
}

/**
 * Schema for trained model information
 * Backend: ModelInfo in schemas/training.py (lines 176-186)
 */
export interface ModelInfo {
  model_id: string;
  model_path: string;
  model_type: string;  // Default: "prophet"
  training_samples: number;
  features: string[];
  hyperparameters: Record<string, any>;
  training_metrics: Record<string, number>;
  trained_at: string;  // ISO datetime string
  data_period: Record<string, string>;
}

/**
 * Schema for individual product training result (with model info)
 * Backend: ProductTrainingResult in schemas/training.py (lines 189-197)
 */
export interface ProductTrainingResultDetailed {
  inventory_product_id: string;
  status: string;
  model_info?: ModelInfo | null;
  data_points: number;
  error_message?: string | null;
  trained_at: string;  // ISO datetime string
  training_duration_seconds?: number | null;
}

/**
 * Response schema for complete training results
 * Backend: TrainingResultsResponse in schemas/training.py (lines 200-220)
 */
export interface TrainingResultsResponse {
  job_id: string;
  tenant_id: string;
  status: TrainingStatus;
  products_trained: number;
  products_failed: number;
  total_products: number;
  training_results: Record<string, ProductTrainingResultDetailed>;
  summary: Record<string, any>;
  completed_at: string;  // ISO datetime string
}

/**
 * Schema for training data validation results
 * Backend: TrainingValidationResult in schemas/training.py (lines 223-230)
 */
export interface TrainingValidationResult {
  is_valid: boolean;
  issues: string[];  // Default: []
  recommendations: string[];  // Default: []
  estimated_time_minutes: number;
  products_analyzed: number;
  total_data_points: number;
}

/**
 * Schema for training performance metrics
 * Backend: TrainingMetrics in schemas/training.py (lines 233-241)
 */
export interface TrainingMetrics {
  mae: number;  // Mean Absolute Error
  mse: number;  // Mean Squared Error
  rmse: number;  // Root Mean Squared Error
  mape: number;  // Mean Absolute Percentage Error
  r2_score: number;  // R-squared score
  mean_actual: number;
  mean_predicted: number;
}

// ================================================================
// CONFIGURATION TYPES
// ================================================================

/**
 * Configuration for external data sources
 * Backend: ExternalDataConfig in schemas/training.py (lines 244-255)
 */
export interface ExternalDataConfig {
  weather_enabled?: boolean;  // Default: true
  traffic_enabled?: boolean;  // Default: true
  weather_features?: string[];  // Default: ["temperature", "precipitation", "humidity"]
  traffic_features?: string[];  // Default: ["traffic_volume"]
}

/**
 * Complete training job configuration
 * Backend: TrainingJobConfig in schemas/training.py (lines 258-277)
 */
export interface TrainingJobConfig {
  external_data?: ExternalDataConfig;
  prophet_params?: Record<string, any>;  // Default: seasonality_mode="additive", etc.
  data_filters?: Record<string, any>;  // Default: {}
  validation_params?: Record<string, any>;  // Default: {min_data_points: 30}
}

/**
 * Response schema for trained model information
 * Backend: TrainedModelResponse in schemas/training.py (lines 280-305)
 */
export interface TrainedModelResponse {
  model_id: string;
  tenant_id: string;
  inventory_product_id: string;
  model_type: string;
  model_path: string;
  version: number;
  training_samples: number;
  features: string[];
  hyperparameters: Record<string, any>;
  training_metrics: Record<string, number>;
  is_active: boolean;
  created_at: string;  // ISO datetime string
  data_period_start?: string | null;  // ISO datetime string
  data_period_end?: string | null;  // ISO datetime string
}

/**
 * Schema for model training statistics
 * Backend: ModelTrainingStats in schemas/training.py (lines 308-314)
 */
export interface ModelTrainingStats {
  total_models: number;
  active_models: number;
  last_training_date?: string | null;  // ISO datetime string
  avg_training_time_minutes: number;
  success_rate: number;  // 0-1
}

/**
 * Response schema for scheduled training jobs
 * Backend: TrainingScheduleResponse in schemas/training.py (lines 325-331)
 */
export interface TrainingScheduleResponse {
  schedule_id: string;
  tenant_ids: string[];
  scheduled_time: string;  // ISO datetime string
  status: string;
  created_at: string;  // ISO datetime string
}

// ================================================================
// WEBSOCKET MESSAGE TYPES
// ================================================================

/**
 * WebSocket message for training progress updates
 * Backend: TrainingProgressUpdate in schemas/training.py (lines 335-339)
 */
export interface TrainingProgressUpdate {
  type: 'training_progress';
  job_id: string;
  progress: TrainingJobProgress;
}

/**
 * WebSocket message for training completion
 * Backend: TrainingCompletedUpdate in schemas/training.py (lines 342-346)
 */
export interface TrainingCompletedUpdate {
  type: 'training_completed';
  job_id: string;
  results: TrainingResultsResponse;
}

/**
 * WebSocket message for training errors
 * Backend: TrainingErrorUpdate in schemas/training.py (lines 349-354)
 */
export interface TrainingErrorUpdate {
  type: 'training_error';
  job_id: string;
  error: string;
  timestamp: string;  // ISO datetime string
}

/**
 * Union type for all WebSocket messages
 * Backend: TrainingWebSocketMessage in schemas/training.py (lines 375-379)
 */
export type TrainingWebSocketMessage =
  | TrainingProgressUpdate
  | TrainingCompletedUpdate
  | TrainingErrorUpdate;

/**
 * Response schema for model performance metrics
 * Backend: ModelMetricsResponse in schemas/training.py (lines 357-372)
 */
export interface ModelMetricsResponse {
  model_id: string;
  accuracy: number;  // R2 score
  mape: number;  // Mean Absolute Percentage Error
  mae: number;  // Mean Absolute Error
  rmse: number;  // Root Mean Square Error
  r2_score: number;
  training_samples: number;
  features?: string[];  // Features used by the model
  model_type: string;
  created_at?: string | null;  // ISO datetime string
  last_used_at?: string | null;  // ISO datetime string
}
