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

void main() {
  late ComfyUiApi api;
  late MockClient mockClient;

  const String testHost = 'http://localhost:8188';

  setUp(() {
    // Setup a MockClient that simulates real API responses
    mockClient = MockClient((request) async {
      final uri = request.url;
      final method = request.method;

      // Simulate queue endpoint
      if (uri.path == '/queue' && method == 'GET') {
        return http.Response(
          jsonEncode({'queue_running': 0, 'queue': [], 'queue_pending': {}}),
          200,
        );
      }

      // Simulate history endpoint
      if (uri.path == '/api/history' && method == 'GET') {
        return http.Response(
          jsonEncode({
            'History': {
              '123456789': {
                'prompt': {
                  // Simplified prompt data
                  '1': {'class_type': 'TestNode'}
                },
                'outputs': {
                  '8': {
                    'images': {
                      'filename': 'ComfyUI_00001_.png',
                      'subfolder': '',
                      'type': 'output',
                    }
                  }
                }
              }
            }
          }),
          200,
        );
      }

      // Simulate checkpoint list endpoint
      if (uri.path == '/api/experiment/models/checkpoints' && method == 'GET') {
        return http.Response(
          jsonEncode({
            'models/checkpoints/dreamshaper_8.safetensors': {
              'filename': 'dreamshaper_8.safetensors',
              'folder': 'models/checkpoints',
            }
          }),
          200,
        );
      }

      // Simulate checkpoint metadata endpoint
      if (uri.path == '/api/view_metadata/checkpoints' && method == 'GET') {
        return http.Response(
          jsonEncode({
            'model': {
              'type': 'checkpoint',
              'title': 'Dreamshaper 8',
              'hash': 'abcdef1234567890',
            }
          }),
          200,
        );
      }

      // Simulate object info endpoint
      if (uri.path == '/api/object_info' && method == 'GET') {
        return http.Response(
          jsonEncode({
            'KSampler': {
              'input': {
                'required': {
                  'model': 'MODEL',
                  'seed': 'INT',
                  'steps': 'INT',
                }
              },
              'output': ['LATENT'],
              'output_is_list': [false]
            }
          }),
          200,
        );
      }

      // Simulate prompt submission endpoint
      if (uri.path == '/api/prompt' && method == 'POST') {
        return http.Response(
          jsonEncode(
              {'prompt_id': '123456789', 'number': 1, 'status': 'success'}),
          200,
        );
      }

      // Simulate image view endpoint
      if (uri.path == '/api/view' && method == 'GET') {
        // Return a dummy image
        return http.Response.bytes([1, 2, 3, 4], 200,
            headers: {
              'Content-Type': 'image/png',
            });
      }

      // Default response for unhandled routes
      return http.Response('Not Found', 404);
    });

    // Create the API with our mock client
    api = ComfyUiApi(
      host: testHost,
      clientId: 'integration-test-client',
      httpClient: mockClient,
    );
  });

  group('Integration Tests', () {
    test('Get queue information', () async {
      final queue = await api.getQueue();

      expect(queue['queue_running'], equals(0));
      expect(queue['queue'], isEmpty);
      expect(queue['queue_pending'], isA<Map>());
    });

    test('Get history information', () async {
      final history = await api.getHistory();

      expect(history['History'], isA<Map>());
      expect(history['History']['123456789'], isA<Map>());
      expect(history['History']['123456789']['outputs'], isA<Map>());
    });

    test('Get checkpoint list', () async {
      final checkpoints = await api.getCheckpoints();

      expect(checkpoints.keys,
          contains('models/checkpoints/dreamshaper_8.safetensors'));
      expect(
          checkpoints['models/checkpoints/dreamshaper_8.safetensors']
              ['filename'],
          equals('dreamshaper_8.safetensors'));
    });

    test('Get checkpoint metadata', () async {
      final metadata = await api
          .getCheckpointDetails('models/checkpoints/dreamshaper_8.safetensors');

      expect(metadata['model']['type'], equals('checkpoint'));
      expect(metadata['model']['title'], equals('Dreamshaper 8'));
    });

    test('Get object info', () async {
      final info = await api.getObjectInfo();

      expect(info['KSampler'], isA<Map>());
      expect(info['KSampler']['input']['required']['seed'], equals('INT'));
    });

    test('Submit prompt', () async {
      final promptData = {
        'prompt': {
          '1': {
            'inputs': {'text': 'A beautiful landscape'},
            'class_type': 'CLIPTextEncode'
          }
        },
        'client_id': 'integration-test-client'
      };

      final result = await api.submitPrompt(promptData);

      expect(result['prompt_id'], equals('123456789'));
      expect(result['status'], equals('success'));
    });

    test('Get image', () async {
      final imageBytes = await api.getImage('ComfyUI_00001_.png');

      expect(imageBytes, equals([1, 2, 3, 4]));
    });

    test('Handle error response', () async {
      // Create a client that always returns an error
      final errorClient = MockClient((_) async {
        return http.Response('Server Error', 500);
      });

      final errorApi = ComfyUiApi(
        host: testHost,
        clientId: 'error-test-client',
        httpClient: errorClient,
      );

      expect(() => errorApi.getQueue(), throwsA(isA<ComfyUiApiException>()));
    });
  });
}
