<?php

namespace App\Helpers\FirstParty\AI;

use Illuminate\Support\Facades\Http;

class RunwareAI
{
    public static function generateSchnellImage($uuid, $prompt, $width = 1024, $height = 1024)
    {
        $api_key = config('services.runware.api_key');

        try {
            $response = Http::timeout(60)
                ->withHeaders([
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer '.$api_key,
                ])
                ->post('https://api.runware.ai/v1', [
                    [
                        'taskUUID' => $uuid,
                        'taskType' => 'imageInference',
                        'width' => $width,
                        'height' => $height,
                        'numberResults' => 1,
                        'outputFormat' => 'WEBP',
                        'outputType' => ['URL'],
                        'includeCost' => true,
                        'inputImages' => [],
                        'positivePrompt' => $prompt,
                        'model' => 'runware:100@1',
                    ],
                ]);

            // Check if the request was successful
            if ($response->successful()) {
                $data = $response->json();

                // Extract the image URL from the response
                if (isset($data['data']) && count($data['data']) > 0) {
                    $imageData = collect($data['data'])
                        ->where('taskType', 'imageInference')
                        ->first();

                    if ($imageData && isset($imageData['imageURL'])) {
                        return $imageData['imageURL'];
                    }
                }

                throw new \Exception('Image URL not found in response');
            }

            throw new \Exception('API request failed: '.$response->status().' - '.$response->body());
        } catch (\Exception $e) {
            // Log the error or handle as needed
            \Log::error('RunwareAI API Error: '.$e->getMessage());
            throw $e;
        }
    }
}
