import 'dart:convert';

class PalmRecord {
  final int? id;
  final String imagePath;
  final String ripenessClass;
  final double confidence;
  final DateTime timestamp;
  final double x1;
  final double y1;
  final double x2;
  final double y2;
  final List<Map<String, dynamic>> detections;
  final String? batchId;
  final int? inferenceMs;

  PalmRecord({
    this.id,
    required this.imagePath,
    required this.ripenessClass,
    required this.confidence,
    required this.timestamp,
    required this.x1,
    required this.y1,
    required this.x2,
    required this.y2,
    this.detections = const [],
    this.batchId,
    this.inferenceMs,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'image_path': imagePath,
      'ripeness_class': ripenessClass,
      'confidence': confidence,
      'timestamp': timestamp.toIso8601String(),
      'x1': x1,
      'y1': y1,
      'x2': x2,
      'y2': y2,
      'detections': json.encode(detections),
      'batch_id': batchId,
      'inference_ms': inferenceMs,
    };
  }

  factory PalmRecord.fromMap(Map<String, dynamic> map) {
    return PalmRecord(
      id: map['id'],
      imagePath: map['image_path'],
      ripenessClass: map['ripeness_class'],
      confidence: map['confidence'],
      timestamp: DateTime.parse(map['timestamp']),
      x1: map['x1'],
      y1: map['y1'],
      x2: map['x2'],
      y2: map['y2'],
      detections: map['detections'] != null
          ? List<Map<String, dynamic>>.from(json.decode(map['detections']))
          : [],
      batchId: map['batch_id'],
      inferenceMs: map['inference_ms'],
    );
  }

  String toJson() => json.encode(toMap());

  factory PalmRecord.fromJson(String source) => PalmRecord.fromMap(json.decode(source));
}
