import 'dart:io';
import 'package:comfyui_api_sdk/comfyui_api_sdk.dart';

void main() async {
  // Create the API client
  final api = ComfyUiApi(host: 'http://mennos-server:7860');

  // Connect to the WebSocket for progress updates
  await api.connectWebSocket();

  // Listen for progress updates
  api.progressUpdates.listen((update) {
    print('Progress update: $update');
  });

  // Get available checkpoints
  final checkpoints = await api.getCheckpoints();
  print('Available checkpoints: ${checkpoints.keys.join(', ')}');

  // Get queue status
  final queue = await api.getQueue();
  print('Queue status: $queue');

  // Submit a basic text-to-image prompt
  final promptWorkflow = {
    "prompt": {
      "3": {
        "inputs": {
          "seed": 123456789,
          "steps": 20,
          "cfg": 7,
          "sampler_name": "euler_ancestral",
          "scheduler": "normal",
          "denoise": 1,
          "model": ["4", 0],
          "positive": ["6", 0],
          "negative": ["7", 0],
          "latent_image": ["5", 0]
        },
        "class_type": "KSampler"
      },
      "4": {
        "inputs": {"ckpt_name": "dreamshaper_8.safetensors"},
        "class_type": "CheckpointLoaderSimple"
      },
      "5": {
        "inputs": {"width": 512, "height": 512, "batch_size": 1},
        "class_type": "EmptyLatentImage"
      },
      "6": {
        "inputs": {
          "text": "a beautiful landscape with mountains and a lake",
          "clip": ["4", 1]
        },
        "class_type": "CLIPTextEncode"
      },
      "7": {
        "inputs": {
          "text": "ugly, blurry, low quality",
          "clip": ["4", 1]
        },
        "class_type": "CLIPTextEncode"
      },
      "8": {
        "inputs": {
          "samples": ["3", 0],
          "vae": ["4", 2]
        },
        "class_type": "VAEDecode"
      },
      "9": {
        "inputs": {
          "filename_prefix": "ComfyUI",
          "images": ["8", 0]
        },
        "class_type": "SaveImage"
      }
    },
    "client_id": api.clientId
  };

  try {
    final result = await api.submitPrompt(promptWorkflow);
    print('Prompt submitted: $result');
  } catch (e) {
    print('Error submitting prompt: $e');
  }

  // Wait for some time to receive WebSocket messages
  await Future.delayed(Duration(seconds: 60));

  // Clean up
  api.dispose();
}
