<?php

namespace App\Services;

use App\FaceSwapJob;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class FaceSwapService
{
	public function swap(FaceSwapJob $job)
	{
		try {
			if (!file_exists($job->source_path)) {
				throw new \Exception("Source image not found: {$job->source_path}");
			}
			if (!file_exists($job->target_path)) {
				throw new \Exception("Target image not found: {$job->target_path}");
			}
			
			$outputDir = dirname($job->output_path);
			if (!file_exists($outputDir)) {
				mkdir($outputDir, 0755, true);
			}
			
			$response = Http::timeout(config('faceswap.timeout'))
				->retry(config('faceswap.retries'), 100)
				->post(config('faceswap.url') . "/faceswap", [
					'job_id'      => $job->id,
					'source_path' => $job->source_path,
					'target_path' => $job->target_path,
					'output_path' => $job->output_path
				]);
			
			if (!$response->successful()) {
				$job->update([
					'status' => 'failed',
					'error'  => $response->body()
				]);
				
				Log::error('Face swap service error', [
					'job_id'   => $job->id,
					'code'     => $job->code,
					'response' => $response->body(),
					'status'   => $response->status()
				]);
				
				throw new \Exception('Face swap service error: ' . $response->body());
			}
			
			$responseData = $response->json();
			if (!isset($responseData['status']) || $responseData['status'] !== 'accepted') {
				throw new \Exception('Invalid response from face swap service');
			}
		} catch (\Exception $e) {
			Log::error('Face swap job error', [
				'job_id' => $job->id ?? null,
				'code'   => $job->code,
				'error'  => $e->getMessage(),
				'trace'  => $e->getTraceAsString()
			]);
			
			if (isset($job)) {
				$job->update([
					'status' => 'failed',
					'error'  => $e->getMessage()
				]);
			}
			
			throw $e;
		}
	}
	
	public function check() {
		$response = Http::get(config('faceswap.url') . "/health");
		Log::info($response->json());
	}
}