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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f203fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/**
 * Pollinations Image Service
 *
 * Functions for interacting with the Pollinations Image API
 */

/**
 * Generates an image URL from a text prompt using the Pollinations Image API
 *
 * @param {string} prompt - The text description of the image to generate
 * @param {string} [model='flux'] - Model name to use for generation
 * @param {number} [seed] - Seed for reproducible results (defaults to random if not specified)
 * @param {number} [width=1024] - Width of the generated image
 * @param {number} [height=1024] - Height of the generated image
 * @param {boolean} [enhance=true] - Whether to enhance the prompt using an LLM before generating
 * @param {boolean} [safe=false] - Whether to apply content filtering
 * @param {boolean} [transparent=false] - Generate image with transparent background (gptimage model only)
 * @param {Object} [authConfig] - Optional authentication configuration {token, referrer}
 * @returns {Object} - Object containing the image URL and metadata
 * @note Always includes nologo=true and private=true parameters
 */
export async function generateImageUrl(prompt, model = 'flux', seed = Math.floor(Math.random() * 1000000), width = 1024, height = 1024, enhance = true, safe = false, transparent = false, authConfig = null) {
  if (!prompt || typeof prompt !== 'string') {
    throw new Error('Prompt is required and must be a string');
  }

  // Parameters are now directly passed as function arguments

  // Build the query parameters
  const queryParams = new URLSearchParams();

  // Always include model (with default 'flux')
  queryParams.append('model', model);

  // Add other parameters
  if (seed !== undefined) queryParams.append('seed', seed);
  if (width) queryParams.append('width', width);
  if (height) queryParams.append('height', height);

  // Add enhance parameter if true
  if (enhance) queryParams.append('enhance', 'true');

  // Add parameters
  queryParams.append('nologo', 'true'); // Always set nologo to true
  queryParams.append('private', 'true'); // Always set private to true)
  queryParams.append('safe', safe.toString()); // Use the customizable safe parameter
  if (transparent) queryParams.append('transparent', 'true'); // Add transparent parameter if true

  // Construct the URL
  const encodedPrompt = encodeURIComponent(prompt);
  const baseUrl = 'https://image.pollinations.ai';
  let url = `${baseUrl}/prompt/${encodedPrompt}`;

  // Add query parameters
  const queryString = queryParams.toString();
  url += `?${queryString}`;

  // Return the URL directly, keeping it simple
  return {
    imageUrl: url,
    prompt,
    width,
    height,
    model,
    seed,
    enhance,
    private: true,
    nologo: true,
    safe,
    transparent
  };
}

/**
 * Generates an image from a text prompt and returns the image data as base64
 * Saves the image to a file by default
 *
 * @param {string} prompt - The text description of the image to generate
 * @param {string} [model='flux'] - Model name to use for generation
 * @param {number} [seed] - Seed for reproducible results (defaults to random if not specified)
 * @param {number} [width=1024] - Width of the generated image
 * @param {number} [height=1024] - Height of the generated image
 * @param {boolean} [enhance=true] - Whether to enhance the prompt using an LLM before generating
 * @param {boolean} [safe=false] - Whether to apply content filtering
 * @param {boolean} [transparent=false] - Generate image with transparent background (gptimage model only)
 * @param {string} [outputPath='./mcpollinations-output'] - Directory path where to save the image
 * @param {string} [fileName] - Name of the file to save (without extension)
 * @param {string} [format='png'] - Image format to save as (png, jpeg, jpg, webp)
 * @param {Object} [authConfig] - Optional authentication configuration {token, referrer}
 * @returns {Promise<Object>} - Object containing the base64 image data, mime type, metadata, and file path if saved
 * @note Always includes nologo=true and private=true parameters
 */
export async function generateImage(prompt, model = 'flux', seed = Math.floor(Math.random() * 1000000), width = 1024, height = 1024, enhance = true, safe = false, transparent = false, outputPath = './mcpollinations-output', fileName = '', format = 'png', authConfig = null) {
  if (!prompt || typeof prompt !== 'string') {
    throw new Error('Prompt is required and must be a string');
  }

  // First, generate the image URL
  const urlResult = await generateImageUrl(prompt, model, seed, width, height, enhance, safe, transparent, authConfig);

  try {
    // Prepare fetch options with optional auth headers
    const fetchOptions = {};
    if (authConfig) {
      fetchOptions.headers = {};
      if (authConfig.token) {
        fetchOptions.headers['Authorization'] = `Bearer ${authConfig.token}`;
      }
      if (authConfig.referrer) {
        fetchOptions.headers['Referer'] = authConfig.referrer;
      }
    }

    // Fetch the image from the URL
    const response = await fetch(urlResult.imageUrl, fetchOptions);

    if (!response.ok) {
      throw new Error(`Failed to generate image: ${response.statusText}`);
    }

    // Get the image data as an ArrayBuffer
    const imageBuffer = await response.arrayBuffer();

    // Convert the ArrayBuffer to a base64 string
    const base64Data = Buffer.from(imageBuffer).toString('base64');

    // Determine the mime type from the response headers or default to image/jpeg
    const contentType = response.headers.get('content-type') || 'image/jpeg';

    // Prepare the result object
    const result = {
      data: base64Data,
      mimeType: contentType,
      metadata: {
        prompt: urlResult.prompt,
        width: urlResult.width,
        height: urlResult.height,
        model: urlResult.model,
        seed: urlResult.seed,
        enhance: urlResult.enhance,
        private: urlResult.private,
        nologo: urlResult.nologo,
        safe: urlResult.safe,
        transparent: urlResult.transparent
      }
    };

    // Always save the image to a file
    // Import required modules
    const fs = await import('fs');
    const path = await import('path');

    // Create the output directory if it doesn't exist
    if (!fs.existsSync(outputPath)) {
      fs.mkdirSync(outputPath, { recursive: true });
    }

    // Validate the file format
    const validFormats = ['png', 'jpeg', 'jpg', 'webp'];
    if (!validFormats.includes(format)) {
      console.warn(`Invalid format '${format}', defaulting to 'png'`);
    }
    const extension = validFormats.includes(format) ? format : 'png';

    // Generate a file name if not provided or ensure it's unique
    let baseFileName = fileName;
    if (!baseFileName) {
      // Create a safe filename from the prompt (first 20 chars, alphanumeric only)
      const safePrompt = prompt.slice(0, 20).replace(/[^a-z0-9]/gi, '_').toLowerCase();
      const timestamp = Date.now();
      // Add a random component to ensure uniqueness
      const randomSuffix = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      baseFileName = `${safePrompt}_${timestamp}_${randomSuffix}`;
    }

    // Ensure the filename is unique to prevent overwriting
    let fileNameWithSuffix = baseFileName;
    let filePath = path.join(outputPath, `${fileNameWithSuffix}.${extension}`);
    let counter = 1;

    // If the file already exists, add a numeric suffix
    while (fs.existsSync(filePath)) {
      fileNameWithSuffix = `${baseFileName}_${counter}`;
      filePath = path.join(outputPath, `${fileNameWithSuffix}.${extension}`);
      counter++;
    }

    // Save the image to the file
    fs.writeFileSync(filePath, Buffer.from(base64Data, 'base64'));

    // Add the file path to the result
    result.filePath = filePath;

    return result;
  } catch (error) {
    console.error('Error generating image:', error);
    throw error;
  }
}

/**
 * Edits or modifies an existing image based on a text prompt
 *
 * @param {string} prompt - The text description of how to edit the image
 * @param {string} imageUrl - URL of the input image to edit
 * @param {string} [model='gptimage'] - Model name to use for editing (gptimage or kontext)
 * @param {number} [seed] - Seed for reproducible results (defaults to random if not specified)
 * @param {number} [width=1024] - Width of the generated image
 * @param {number} [height=1024] - Height of the generated image
 * @param {boolean} [enhance=true] - Whether to enhance the prompt using an LLM before generating
 * @param {boolean} [safe=false] - Whether to apply content filtering
 * @param {boolean} [transparent=false] - Generate image with transparent background (gptimage model only)
 * @param {string} [outputPath='./mcpollinations-output'] - Directory path where to save the image
 * @param {string} [fileName] - Name of the file to save (without extension)
 * @param {string} [format='png'] - Image format to save as (png, jpeg, jpg, webp)
 * @param {Object} [authConfig] - Optional authentication configuration {token, referrer}
 * @returns {Promise<Object>} - Object containing the base64 image data, mime type, metadata, and file path if saved
 * @note Always includes nologo=true and private=true parameters
 */
export async function editImage(prompt, imageUrl, model = 'gptimage', seed = Math.floor(Math.random() * 1000000), width = 1024, height = 1024, enhance = true, safe = false, transparent = false, outputPath = './mcpollinations-output', fileName = '', format = 'png', authConfig = null) {
  if (!prompt || typeof prompt !== 'string') {
    throw new Error('Prompt is required and must be a string');
  }

  if (!imageUrl || typeof imageUrl !== 'string') {
    throw new Error('Image URL is required and must be a string');
  }

  // Build the query parameters
  const queryParams = new URLSearchParams();
  queryParams.append('model', model);
  queryParams.append('image', imageUrl); // Add the input image URL
  if (seed !== undefined) queryParams.append('seed', seed);
  if (width !== 1024) queryParams.append('width', width);
  if (height !== 1024) queryParams.append('height', height);

  // Add enhance parameter if true
  if (enhance) queryParams.append('enhance', 'true');

  // Add parameters
  queryParams.append('nologo', 'true'); // Always set nologo to true
  queryParams.append('private', 'true'); // Always set private to true)
  queryParams.append('safe', safe.toString()); // Use the customizable safe parameter
  if (transparent) queryParams.append('transparent', 'true'); // Add transparent parameter if true

  // Construct the URL
  const encodedPrompt = encodeURIComponent(prompt);
  const baseUrl = 'https://image.pollinations.ai';
  let url = `${baseUrl}/prompt/${encodedPrompt}`;

  // Add query parameters
  const queryString = queryParams.toString();
  url += `?${queryString}`;

  try {
    // Prepare fetch options with optional auth headers
    const fetchOptions = {};
    if (authConfig) {
      fetchOptions.headers = {};
      if (authConfig.token) {
        fetchOptions.headers['Authorization'] = `Bearer ${authConfig.token}`;
      }
      if (authConfig.referrer) {
        fetchOptions.headers['Referer'] = authConfig.referrer;
      }
    }

    // Fetch the image from the URL
    const response = await fetch(url, fetchOptions);

    if (!response.ok) {
      throw new Error(`Failed to edit image: ${response.statusText}`);
    }

    // Get the image data as an ArrayBuffer
    const imageBuffer = await response.arrayBuffer();

    // Convert the ArrayBuffer to a base64 string
    const base64Data = Buffer.from(imageBuffer).toString('base64');

    // Determine the mime type from the response headers or default to image/jpeg
    const contentType = response.headers.get('content-type') || 'image/jpeg';

    // Prepare the result object
    const result = {
      data: base64Data,
      mimeType: contentType,
      metadata: {
        prompt,
        inputImageUrl: imageUrl,
        width,
        height,
        model,
        seed,
        enhance,
        private: true,
        nologo: true,
        safe,
        transparent
      }
    };

    // Always save the image to a file
    // Import required modules
    const fs = await import('fs');
    const path = await import('path');

    // Create the output directory if it doesn't exist
    if (!fs.existsSync(outputPath)) {
      fs.mkdirSync(outputPath, { recursive: true });
    }

    // Generate a filename if not provided
    let finalFileName = fileName;
    if (!finalFileName) {
      // Create a filename from the prompt (first 20 characters) and timestamp
      const sanitizedPrompt = prompt.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 20);
      const timestamp = Date.now();
      const randomSuffix = Math.floor(Math.random() * 1000);
      finalFileName = `edited_${sanitizedPrompt}_${timestamp}_${randomSuffix}`;
    }

    // Ensure the filename has the correct extension
    const extension = format.toLowerCase();
    if (!finalFileName.endsWith(`.${extension}`)) {
      finalFileName += `.${extension}`;
    }

    // Check if file already exists and add a number suffix if needed
    let finalFilePath = path.join(outputPath, finalFileName);
    let counter = 1;
    while (fs.existsSync(finalFilePath)) {
      const nameWithoutExt = finalFileName.replace(`.${extension}`, '');
      const numberedFileName = `${nameWithoutExt}_${counter}.${extension}`;
      finalFilePath = path.join(outputPath, numberedFileName);
      counter++;
    }

    // Write the image data to the file
    fs.writeFileSync(finalFilePath, Buffer.from(base64Data, 'base64'));

    // Add the file path to the result
    result.filePath = finalFilePath;

    return result;

  } catch (error) {
    console.error('Error editing image:', error);
    throw error;
  }
}

/**
 * Generates a new image using an existing image as reference
 *
 * @param {string} prompt - The text description of what to generate based on the reference image
 * @param {string} imageUrl - URL of the reference image
 * @param {string} [model='gptimage'] - Model name to use for generation (gptimage or kontext)
 * @param {number} [seed] - Seed for reproducible results (defaults to random if not specified)
 * @param {number} [width=1024] - Width of the generated image
 * @param {number} [height=1024] - Height of the generated image
 * @param {boolean} [enhance=true] - Whether to enhance the prompt using an LLM before generating
 * @param {boolean} [safe=false] - Whether to apply content filtering
 * @param {boolean} [transparent=false] - Generate image with transparent background (gptimage model only)
 * @param {string} [outputPath='./mcpollinations-output'] - Directory path where to save the image
 * @param {string} [fileName] - Name of the file to save (without extension)
 * @param {string} [format='png'] - Image format to save as (png, jpeg, jpg, webp)
 * @param {Object} [authConfig] - Optional authentication configuration {token, referrer}
 * @returns {Promise<Object>} - Object containing the base64 image data, mime type, metadata, and file path if saved
 * @note Always includes nologo=true and private=true parameters
 */
export async function generateImageFromReference(prompt, imageUrl, model = 'gptimage', seed = Math.floor(Math.random() * 1000000), width = 1024, height = 1024, enhance = true, safe = false, transparent = false, outputPath = './mcpollinations-output', fileName = '', format = 'png', authConfig = null) {
  if (!prompt || typeof prompt !== 'string') {
    throw new Error('Prompt is required and must be a string');
  }

  if (!imageUrl || typeof imageUrl !== 'string') {
    throw new Error('Reference image URL is required and must be a string');
  }

  // Build the query parameters
  const queryParams = new URLSearchParams();
  queryParams.append('model', model);
  queryParams.append('image', imageUrl); // Add the reference image URL
  if (seed !== undefined) queryParams.append('seed', seed);
  if (width !== 1024) queryParams.append('width', width);
  if (height !== 1024) queryParams.append('height', height);

  // Add enhance parameter if true
  if (enhance) queryParams.append('enhance', 'true');

  // Add parameters
  queryParams.append('nologo', 'true'); // Always set nologo to true
  queryParams.append('private', 'true'); // Always set private to true)
  queryParams.append('safe', safe.toString()); // Use the customizable safe parameter
  if (transparent) queryParams.append('transparent', 'true'); // Add transparent parameter if true

  // Construct the URL
  const encodedPrompt = encodeURIComponent(prompt);
  const baseUrl = 'https://image.pollinations.ai';
  let url = `${baseUrl}/prompt/${encodedPrompt}`;

  // Add query parameters
  const queryString = queryParams.toString();
  url += `?${queryString}`;

  try {
    // Prepare fetch options with optional auth headers
    const fetchOptions = {};
    if (authConfig) {
      fetchOptions.headers = {};
      if (authConfig.token) {
        fetchOptions.headers['Authorization'] = `Bearer ${authConfig.token}`;
      }
      if (authConfig.referrer) {
        fetchOptions.headers['Referer'] = authConfig.referrer;
      }
    }

    // Fetch the image from the URL
    const response = await fetch(url, fetchOptions);

    if (!response.ok) {
      throw new Error(`Failed to generate image from reference: ${response.statusText}`);
    }

    // Get the image data as an ArrayBuffer
    const imageBuffer = await response.arrayBuffer();

    // Convert the ArrayBuffer to a base64 string
    const base64Data = Buffer.from(imageBuffer).toString('base64');

    // Determine the mime type from the response headers or default to image/jpeg
    const contentType = response.headers.get('content-type') || 'image/jpeg';

    // Prepare the result object
    const result = {
      data: base64Data,
      mimeType: contentType,
      metadata: {
        prompt,
        referenceImageUrl: imageUrl,
        width,
        height,
        model,
        seed,
        enhance,
        private: true,
        nologo: true,
        safe,
        transparent
      }
    };

    // Always save the image to a file
    // Import required modules
    const fs = await import('fs');
    const path = await import('path');

    // Create the output directory if it doesn't exist
    if (!fs.existsSync(outputPath)) {
      fs.mkdirSync(outputPath, { recursive: true });
    }

    // Generate a filename if not provided
    let finalFileName = fileName;
    if (!finalFileName) {
      // Create a filename from the prompt (first 20 characters) and timestamp
      const sanitizedPrompt = prompt.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 20);
      const timestamp = Date.now();
      const randomSuffix = Math.floor(Math.random() * 1000);
      finalFileName = `reference_${sanitizedPrompt}_${timestamp}_${randomSuffix}`;
    }

    // Ensure the filename has the correct extension
    const extension = format.toLowerCase();
    if (!finalFileName.endsWith(`.${extension}`)) {
      finalFileName += `.${extension}`;
    }

    // Check if file already exists and add a number suffix if needed
    let finalFilePath = path.join(outputPath, finalFileName);
    let counter = 1;
    while (fs.existsSync(finalFilePath)) {
      const nameWithoutExt = finalFileName.replace(`.${extension}`, '');
      const numberedFileName = `${nameWithoutExt}_${counter}.${extension}`;
      finalFilePath = path.join(outputPath, numberedFileName);
      counter++;
    }

    // Write the image data to the file
    fs.writeFileSync(finalFilePath, Buffer.from(base64Data, 'base64'));

    // Add the file path to the result
    result.filePath = finalFilePath;

    return result;

  } catch (error) {
    console.error('Error generating image from reference:', error);
    throw error;
  }
}

/**
 * List available image generation models from Pollinations API
 *
 * @returns {Promise<Object>} - Object containing the list of available image models
 */
export async function listImageModels() {
  try {
    const response = await fetch('https://image.pollinations.ai/models');

    if (!response.ok) {
      throw new Error(`Failed to list models: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Error listing image models:', error);
    throw error;
  }
}