<?php

namespace App\Services\FaceSwap;

use App\Contracts\FaceSwapDriverInterface;
use Illuminate\Support\Facades\Http;

class SegmindDriver implements FaceSwapDriverInterface
{
    protected string $apiUrl;
    protected string $apiKey;
    protected int $timeout;

    public function __construct()
    {
        $this->apiUrl = config('faceswap.drivers.segmind.api_url');
        $this->apiKey = config('faceswap.drivers.segmind.api_key');
        $this->timeout = (int) config('faceswap.drivers.segmind.timeout', 90);
    }

    public function process(string $faceImageData, string $productImageData): string
    {
        $response = Http::timeout($this->timeout)
            ->withHeaders([
                'x-api-key' => $this->apiKey,
                'Content-Type' => 'application/json',
            ])
            ->post($this->apiUrl, [
                'source_img' => $this->toBase64DataUri($faceImageData),
                'target_img' => $this->toBase64DataUri($productImageData),
            ]);

        if (!$response->successful()) {
            throw new \Exception('Segmind API error: HTTP ' . $response->status());
        }

        $body = $response->body();
        $contentType = strtolower((string) $response->header('Content-Type'));

        if (str_contains($contentType, 'application/json')) {
            $decoded = json_decode($body, true);
            if (is_array($decoded) && isset($decoded['image'])) {
                return base64_decode($decoded['image']);
            }
            throw new \Exception('Segmind API returned unexpected JSON payload');
        }

        return $body;
    }

    protected function toBase64DataUri(string $imageData): string
    {
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->buffer($imageData) ?: 'image/jpeg';

        return 'data:' . $mimeType . ';base64,' . base64_encode($imageData);
    }
}
