// import 'dart:convert';
// import 'dart:io';

// import 'package:dio/dio.dart';
// import 'package:image_picker/image_picker.dart';
// import 'package:sigap/src/features/auth/data/models/face_model.dart';
// import 'package:sigap/src/utils/constants/api_urls.dart';
// import 'package:sigap/src/utils/dio.client/dio_client.dart';
// import 'package:sigap/src/utils/helpers/aws_signature.dart';

// class AwsRecognitionService {
//   // Singleton instance
//   static final AwsRecognitionService instance = AwsRecognitionService._();
//   AwsRecognitionService._();

//   // AWS Recognition API configuration
//   final String region = Endpoints.awsRegion;
//   final String accessKey = Endpoints.awsAccessKey;
//   final String secretKey = Endpoints.awsSecretKey;
//   final String serviceEndpoint = Endpoints.awsRekognitionEndpoint;
//   final String serviceName = 'rekognition';

//   // Face detection threshold values
//   final double faceMatchThreshold =
//       80.0; // Minimum confidence for face match (0-100)

//   // Detect faces in an image and return face details
//   Future<List<FaceModel>> detectFaces(XFile imageFile) async {
//     try {
//       final bytes = await File(imageFile.path).readAsBytes();
//       final base64Image = base64Encode(bytes);

//       // Create AWS Signature
//       final awsSignature = AwsSignature(
//         accessKey: accessKey,
//         secretKey: secretKey,
//         region: region,
//         serviceName: serviceName,
//       );

//       // Prepare request payload
//       final payload = {
//         'Image': {'Bytes': base64Image},
//         'Attributes': ['DEFAULT'],
//       };

//       // Get signed headers and URL
//       final dateTime = DateTime.now().toUtc();
//       final uri = Uri.parse('$serviceEndpoint/DetectFaces');
//       final headers = awsSignature.buildRequestHeaders(
//         method: 'POST',
//         uri: uri,
//         payload: payload,
//         dateTime: dateTime,
//       );

//       // Make API request
//       final response = await DioClient().post(
//         uri.toString(),
//         data: payload,
//         options: Options(headers: headers, responseType: ResponseType.json),
//       );

//       if (response.statusCode == 200) {
//         final faceDetails = response.data['FaceDetails'];
//         // Convert AWS response to FaceModel objects
//         List<FaceModel> faces = [];
//         for (var i = 0; i < faceDetails.length; i++) {
//           String faceId = 'face_${dateTime.millisecondsSinceEpoch}_$i';
//           faces.add(FaceModel.fromDetection(faceId, imageFile, faceDetails[i]));
//         }
//         return faces;
//       } else {
//         throw Exception(
//           'Failed to detect faces: ${response.statusCode} - ${response.data}',
//         );
//       }
//     } catch (e) {
//       print('Face detection error: $e');
//       return [];
//     }
//   }

//   // Compare two face images and return comparison result
//   Future<FaceComparisonResult> compareFaces(
//     XFile sourceImage,
//     XFile targetImage,
//   ) async {
//     try {
//       // First detect faces in both images
//       List<FaceModel> sourceFaces = await detectFaces(sourceImage);
//       List<FaceModel> targetFaces = await detectFaces(targetImage);

//       if (sourceFaces.isEmpty || targetFaces.isEmpty) {
//         return FaceComparisonResult.noMatch(
//           sourceFaces.isEmpty ? FaceModel.empty() : sourceFaces.first,
//           targetFaces.isEmpty ? FaceModel.empty() : targetFaces.first,
//           message:
//               sourceFaces.isEmpty && targetFaces.isEmpty
//                   ? 'No faces detected in either image'
//                   : sourceFaces.isEmpty
//                   ? 'No face detected in ID card image'
//                   : 'No face detected in selfie image',
//         );
//       }

//       // Get the primary faces from each image
//       FaceModel sourceFace = sourceFaces.first;
//       FaceModel targetFace = targetFaces.first;

//       final sourceBytes = await File(sourceImage.path).readAsBytes();
//       final targetBytes = await File(targetImage.path).readAsBytes();

//       // Create AWS Signature
//       final awsSignature = AwsSignature(
//         accessKey: accessKey,
//         secretKey: secretKey,
//         region: region,
//         serviceName: serviceName,
//       );

//       // Prepare request payload
//       final payload = {
//         'SourceImage': {'Bytes': base64Encode(sourceBytes)},
//         'TargetImage': {'Bytes': base64Encode(targetBytes)},
//         'SimilarityThreshold': faceMatchThreshold,
//       };

//       // Get signed headers and URL
//       final dateTime = DateTime.now().toUtc();
//       final uri = Uri.parse('$serviceEndpoint/CompareFaces');
//       final headers = awsSignature.buildRequestHeaders(
//         method: 'POST',
//         uri: uri,
//         payload: payload,
//         dateTime: dateTime,
//       );

//       // Make API request
//       final response = await DioClient().post(
//         uri.toString(),
//         data: payload,
//         options: Options(headers: headers, responseType: ResponseType.json),
//       );

//       if (response.statusCode == 200) {
//         return FaceComparisonResult.fromAwsResponse(
//           sourceFace,
//           targetFace,
//           response.data,
//         );
//       } else {
//         throw Exception(
//           'Failed to compare faces: ${response.statusCode} - ${response.data}',
//         );
//       }
//     } catch (e) {
//       print('Face comparison error: $e');
//       return FaceComparisonResult.error(
//         FaceModel.empty().withMessage('Source face processing error'),
//         FaceModel.empty().withMessage('Target face processing error'),
//         e.toString(),
//       );
//     }
//   }

//   // Perform liveness detection (anti-spoofing check)
//   Future<FaceModel> performLivenessCheck(XFile selfieImage) async {
//     try {
//       // In a real implementation, AWS Recognition doesn't directly offer liveness detection
//       // You might need to use a combination of services or a third-party solution
//       // For now, we'll simulate a successful check by detecting a face
//       final faces = await detectFaces(selfieImage);

//       if (faces.isEmpty) {
//         return FaceModel.empty().withLiveness(
//           isLive: false,
//           confidence: 0.0,
//           message: 'No face detected in the selfie.',
//         );
//       }

//       // Get the primary face
//       FaceModel face = faces.first;

//       // Check confidence of face detection as a basic indicator
//       if (face.detectionConfidence < 0.7) {
//         return face.withLiveness(
//           isLive: false,
//           confidence: face.detectionConfidence,
//           message:
//               'Low confidence face detection. Please take a clearer selfie.',
//         );
//       }

//       // For a full implementation, you might want to:
//       // 1. Check eye blink detection
//       // 2. Analyze multiple facial movements
//       // 3. Use depth information if available

//       return face.withLiveness(
//         isLive: true,
//         confidence: face.detectionConfidence,
//         message: 'Liveness check passed successfully.',
//       );
//     } catch (e) {
//       return FaceModel.empty().withLiveness(
//         isLive: false,
//         confidence: 0.0,
//         message: 'Liveness check error: ${e.toString()}',
//       );
//     }
//   }
// }
