<?php

namespace App\Services\FaceSwap;

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

/**
 * Face-swap driver backed by the kimono-face-pipeline local service.
 *
 * Posts the user face + product (kimono model) image to the pipeline's
 * /swap endpoint (InsightFace inswapper + GFPGAN) and returns the result bytes.
 */
class KimonoPipelineDriver implements FaceSwapDriverInterface
{
    protected string $baseUrl;
    protected int $timeout;
    protected string $provider;

    public function __construct()
    {
        $this->baseUrl = rtrim((string) config('faceswap.drivers.kimonopipeline.url', 'http://127.0.0.1:5005'), '/');
        $this->timeout = (int) config('faceswap.drivers.kimonopipeline.timeout', 120);
        // Which generation engine the pipeline should use: 'local' (inswapper+GFPGAN) or 'chatgpt' (gpt-image).
        $this->provider = (string) config('faceswap.drivers.kimonopipeline.provider', 'local');
    }

    public function process(string $faceImageData, string $productImageData): string
    {
        $response = Http::timeout($this->timeout)
            ->attach('source', $faceImageData, 'source.jpg')
            ->attach('target', $productImageData, 'target.jpg')
            ->post($this->baseUrl . '/swap', ['provider' => $this->provider]);

        if (!$response->successful()) {
            Log::error('KimonoPipeline face swap failed', [
                'status' => $response->status(),
                'body'   => substr($response->body(), 0, 300),
            ]);
            throw new \Exception('Kimono pipeline face swap failed (HTTP ' . $response->status() . ')');
        }

        $body = $response->body();
        if ($body === '') {
            throw new \Exception('Kimono pipeline returned empty result');
        }

        return $body;
    }
}
