// import 'dart:convert';
// import 'dart:io';
// import 'package:http/http.dart' as http;

// class DocumentIntelligenceService {
//   final String endpoint;
//   final String key;
//   final http.Client _client = http.Client();

//   DocumentIntelligenceService({
//     required this.endpoint,
//     required this.key,
//   });

//   // Generator function equivalent for getting text of spans
//   List<String> getTextOfSpans(String content, List<Map<String, dynamic>> spans) {
//     List<String> textList = [];
//     for (var span in spans) {
//       int offset = span['offset'];
//       int length = span['length'];
//       textList.add(content.substring(offset, offset + length));
//     }
//     return textList;
//   }

//   Future<Map<String, dynamic>> analyzeDocument(String documentUrl) async {
//     try {
//       // Initial request to start document analysis
//       final initialResponse = await _client.post(
//         Uri.parse('$endpoint/documentModels/prebuilt-read:analyze'),
//         headers: {
//           'Content-Type': 'application/json',
//           'Ocp-Apim-Subscription-Key': key,
//         },
//         body: jsonEncode({
//           'urlSource': documentUrl,
//         }),
//       );

//       if (initialResponse.statusCode != 202) {
//         throw Exception('Failed to start analysis: ${initialResponse.body}');
//       }

//       // Get operation location from response headers
//       String? operationLocation = initialResponse.headers['operation-location'];
//       if (operationLocation == null) {
//         throw Exception('Operation location not found in response headers');
//       }

//       // Poll for results
//       return await _pollForResults(operationLocation);
//     } catch (e) {
//       throw Exception('Error analyzing document: $e');
//     }
//   }

//   Future<Map<String, dynamic>> _pollForResults(String operationLocation) async {
//     const int maxAttempts = 60; // Maximum polling attempts
//     const Duration pollInterval = Duration(seconds: 2);

//     for (int attempt = 0; attempt < maxAttempts; attempt++) {
//       final response = await _client.get(
//         Uri.parse(operationLocation),
//         headers: {
//           'Ocp-Apim-Subscription-Key': key,
//         },
//       );

//       if (response.statusCode != 200) {
//         throw Exception('Failed to get operation status: ${response.body}');
//       }

//       final responseData = jsonDecode(response.body);
//       final String status = responseData['status'];

//       if (status == 'succeeded') {
//         return responseData['analyzeResult'];
//       } else if (status == 'failed') {
//         throw Exception('Document analysis failed: ${responseData['error']}');
//       }

//       // Wait before next poll
//       await Future.delayed(pollInterval);
//     }

//     throw Exception('Operation timed out after $maxAttempts attempts');
//   }

//   Future<void> processDocument(String documentUrl) async {
//     try {
//       final analyzeResult = await analyzeDocument(documentUrl);
      
//       final String? content = analyzeResult['content'];
//       final List<dynamic>? pages = analyzeResult['pages'];
//       final List<dynamic>? languages = analyzeResult['languages'];
//       final List<dynamic>? styles = analyzeResult['styles'];

//       // Process pages
//       if (pages == null || pages.isEmpty) {
//         print('No pages were extracted from the document.');
//       } else {
//         print('Pages:');
//         for (var page in pages) {
//           print('- Page ${page['pageNumber']} (unit: ${page['unit']})');
//           print('  ${page['width']}x${page['height']}, angle: ${page['angle']}');
          
//           final List<dynamic> lines = page['lines'] ?? [];
//           final List<dynamic> words = page['words'] ?? [];
          
//           print('  ${lines.length} lines, ${words.length} words');
          
//           if (lines.isNotEmpty) {
//             print('  Lines:');
//             for (var line in lines) {
//               print('  - "${line['content']}"');
//             }
//           }
          
//           if (words.isNotEmpty) {
//             print('  Words:');
//             for (var word in words) {
//               print('  - "${word['content']}"');
//             }
//           }
//         }
//       }

//       // Process languages
//       if (languages == null || languages.isEmpty) {
//         print('No language spans were extracted from the document.');
//       } else {
//         print('Languages:');
//         for (var languageEntry in languages) {
//           print('- Found language: ${languageEntry['locale']} '
//                 '(confidence: ${languageEntry['confidence']})');
          
//           if (content != null && languageEntry['spans'] != null) {
//             final spans = List<Map<String, dynamic>>.from(languageEntry['spans']);
//             final textList = getTextOfSpans(content, spans);
            
//             for (var text in textList) {
//               final escapedText = text
//                   .replaceAll(RegExp(r'\r?\n'), '\\n')
//                   .replaceAll('"', '\\"');
//               print('  - "$escapedText"');
//             }
//           }
//         }
//       }

//       // Process styles
//       if (styles == null || styles.isEmpty) {
//         print('No text styles were extracted from the document.');
//       } else {
//         print('Styles:');
//         for (var style in styles) {
//           final bool isHandwritten = style['isHandwritten'] ?? false;
//           final double confidence = style['confidence'] ?? 0.0;
          
//           print('- Handwritten: ${isHandwritten ? "yes" : "no"} '
//                 '(confidence=$confidence)');
          
//           if (content != null && style['spans'] != null) {
//             final spans = List<Map<String, dynamic>>.from(style['spans']);
//             final textList = getTextOfSpans(content, spans);
            
//             for (var text in textList) {
//               print('  - "$text"');
//             }
//           }
//         }
//       }
//     } catch (e) {
//       print('An error occurred: $e');
//     }
//   }

//   void dispose() {
//     _client.close();
//   }
// }

// // Example usage in a Flutter app
// class DocumentAnalyzerApp {
//   static const String endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT";
//   static const String key = "YOUR_FORM_RECOGNIZER_KEY";
//   static const String formUrl = 
//       "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png";

//   static Future<void> main() async {
//     final service = DocumentIntelligenceService(
//       endpoint: endpoint,
//       key: key,
//     );

//     try {
//       await service.processDocument(formUrl);
//     } finally {
//       service.dispose();
//     }
//   }
// }

// // Flutter Widget Example
// import 'package:flutter/material.dart';

// class DocumentAnalyzerWidget extends StatefulWidget {
//   const DocumentAnalyzerWidget({super.key});

//   @override
//   _DocumentAnalyzerWidgetState createState() => _DocumentAnalyzerWidgetState();
// }

// class _DocumentAnalyzerWidgetState extends State<DocumentAnalyzerWidget> {
//   final DocumentIntelligenceService _service = DocumentIntelligenceService(
//     endpoint: "YOUR_FORM_RECOGNIZER_ENDPOINT",
//     key: "YOUR_FORM_RECOGNIZER_KEY",
//   );
  
//   bool _isLoading = false;
//   String _result = '';

//   Future<void> _analyzeDocument() async {
//     setState(() {
//       _isLoading = true;
//       _result = '';
//     });

//     try {
//       const String documentUrl = 
//           "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png";
      
//       await _service.processDocument(documentUrl);
//       setState(() {
//         _result = 'Document analysis completed successfully!';
//       });
//     } catch (e) {
//       setState(() {
//         _result = 'Error: $e';
//       });
//     } finally {
//       setState(() {
//         _isLoading = false;
//       });
//     }
//   }

//   @override
//   void dispose() {
//     _service.dispose();
//     super.dispose();
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text('Document Intelligence'),
//       ),
//       body: Padding(
//         padding: EdgeInsets.all(16.0),
//         child: Column(
//           crossAxisAlignment: CrossAxisAlignment.stretch,
//           children: [
//             ElevatedButton(
//               onPressed: _isLoading ? null : _analyzeDocument,
//               child: _isLoading
//                   ? CircularProgressIndicator(color: Colors.white)
//                   : Text('Analyze Document'),
//             ),
//             SizedBox(height: 20),
//             if (_result.isNotEmpty)
//               Expanded(
//                 child: SingleChildScrollView(
//                   child: Text(
//                     _result,
//                     style: TextStyle(fontSize: 14),
//                   ),
//                 ),
//               ),
//           ],
//         ),
//       ),
//     );
//   }
// }