import 'package:flutter/foundation.dart';

import 'package:mini_tias/services/file_service.dart';
import 'package:mini_tias/services/raw_capture_service.dart';

/// カメラ診断機能の状態管理．
/// Camera2 API の能力を読み出し JSON ファイルに保存する．
class DiagnosticsProvider extends ChangeNotifier {
  final RawCaptureService _rawCaptureService;
  final FileService _fileService;

  DiagnosticsProvider({
    RawCaptureService? rawCaptureService,
    FileService? fileService,
  }) : _rawCaptureService = rawCaptureService ?? RawCaptureService(),
       _fileService = fileService ?? FileService();

  bool _isRunning = false;
  String? _lastSavedPath;
  String? _errorMessage;

  bool get isRunning => _isRunning;
  String? get lastSavedPath => _lastSavedPath;
  String? get errorMessage => _errorMessage;

  /// 診断を実行し，結果を JSON ファイルとして保存する．
  Future<void> runDiagnostics() async {
    if (_isRunning) return;

    _isRunning = true;
    _errorMessage = null;
    _lastSavedPath = null;
    notifyListeners();

    try {
      final diagnostics = await _rawCaptureService.getCameraDiagnostics();
      if (diagnostics == null) {
        _errorMessage = 'カメラ診断情報を取得できませんでした';
        _isRunning = false;
        notifyListeners();
        return;
      }

      final savedPath = await _fileService.saveDiagnosticsJson(diagnostics);
      await _rawCaptureService.scanFile(savedPath);

      _lastSavedPath = savedPath;
    } catch (e) {
      _errorMessage = '診断の実行に失敗しました: $e';
    }

    _isRunning = false;
    notifyListeners();
  }
}
