import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import '../constants/app_constants.dart';
import 'obstacle_analyzer.dart';

class YoloDetector {
  final ObstacleAnalyzer _analyzer;
  List<String> _labels = const [];
  bool _ready = false;

  YoloDetector(this._analyzer);

  bool get isReady => _ready;

  Future<void> init() async {
    try {
      _labels = (await rootBundle.loadString(AppConstants.yoloLabelsPath))
          .split('\n')
          .map((e) => e.trim())
          .where((e) => e.isNotEmpty)
          .toList();
      if (kIsWeb) {
        _ready = false;
        return;
      }
      await rootBundle.load(await AppConstants.getSelectedYoloModelPath());
      _ready = true;
    } catch (e) {
      debugPrint('YOLO fallback mode: $e');
      _ready = false;
    }
  }

  Future<DetectionResult?> detectFallback() async {
    if (_ready) {
      // Full tensor pre/post-processing belongs here once yolov8n.tflite is present.
      // The app keeps a deterministic fallback so demo flows remain testable.
    }
    final label = _labels.isNotEmpty ? _labels.first : 'person';
    return _analyzer.analyzeFallback(label: label);
  }

  void dispose() {
    _ready = false;
  }
}
