<?php

namespace App\Services;

use App\Models\JinaCache;
use App\Models\ApiUsageLog;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class JinaContentExtractor
{
    private string $apiKey;
    private string $baseUrl = 'https://r.jina.ai/';
    private int $rateLimitMs;

    public function __construct()
    {
        $this->apiKey = config('services.jina.api_key');
        $this->rateLimitMs = config('services.jina.rate_limit_ms', 100);
    }

    /**
     * Fetch content from URL with caching
     */
    public function fetchContent(string $url, bool $useCache = true): ?string
    {
        // Check cache first
        if ($useCache) {
            $cached = JinaCache::getCachedContent($url);
            if ($cached) {
                Log::info('Jina cache hit', ['url' => $url]);
                return $cached;
            }
        }

        // Rate limiting
        usleep($this->rateLimitMs * 1000);

        try {
            Log::info('Jina API request', ['url' => $url]);

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Accept' => 'application/json',
            ])
            ->timeout(60)
            ->get($this->baseUrl . $url);

            if (!$response->successful()) {
                throw new \Exception('Jina API request failed: ' . $response->status());
            }

            $data = $response->json();
            $content = $data['content'] ?? '';

            // Limit to 1000 characters
            $content = substr($content, 0, 1000);

            // Cache the result
            if ($useCache && $content) {
                $cacheDays = config('services.jina.cache_days', 30);
                JinaCache::cacheContent($url, $content, $cacheDays);
            }

            // Log API usage
            ApiUsageLog::logUsage('jina', 0.001);

            return $content;

        } catch (\Exception $e) {
            Log::error('Jina API error', [
                'url' => $url,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

    /**
     * Fetch content for multiple URLs in batch
     */
    public function fetchBatch(array $urls, bool $useCache = true): array
    {
        $results = [];

        foreach ($urls as $url) {
            $results[$url] = $this->fetchContent($url, $useCache);
        }

        return $results;
    }
}
