<?php

namespace App\Services;

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

class ImageScraperService
{
    /**
     * Scrape an image from Yandex Images based on the keyword.
     *
     * @param string $keyword
     * @return string|null
     */
    public function scrapeYandexImage(string $keyword): ?string
    {
        try {
            // Encode the keyword for the URL
            $query = urlencode($keyword);
            $url = "https://yandex.com/images/search?text={$query}";

            // Perform the HTTP request with a User-Agent to mimic a real browser
            $response = Http::withHeaders([
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Language' => 'en-US,en;q=0.5',
            ])->get($url);

            if ($response->failed()) {
                Log::warning("Yandex Image Scraper failed to fetch page: {$response->status()}");
                return null;
            }

            $html = html_entity_decode($response->body());

            // Look for "origUrl":"..." or "preview":[{"url":"..."}]
            
            // Try to find high-res original URL first
            if (preg_match('/"origUrl":"([^"]+)"/', $html, $matches)) {
                return $matches[1];
            }

            // Try "url" inside preview (thumbnail or resized)
            if (preg_match('/"url":"([^"]+)"/', $html, $matches)) {
                return $matches[1];
            }
            
            // Legacy/other formats
            if (preg_match('/"img_url":"([^"]+)"/', $html, $matches)) {
                return $matches[1];
            }

            Log::info("Yandex Image Scraper: No image found for keyword '{$keyword}'.");
            return null;

        } catch (\Exception $e) {
            Log::error("Yandex Image Scraper Exception: " . $e->getMessage());
            return null;
        }
    }
}
