<?php
/**
 * API Router — Smart dispatcher
 *
 * Routes API calls to the correct client based on packshotphoto_connection_type option.
 * 'our_service' → CloudClient (uses packshotphoto_api_key via Supabase)
 * 'custom_api'  → OpenAIClient (uses packshotphoto_dev_* options)
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\API;

use PackshotPhotoAI\Core\Logger;

defined('ABSPATH') || exit;

/**
 * Routes between CloudClient and OpenAIClient transparently
 */
class ApiRouter {

    /**
     * @var ClientInterface
     */
    private ClientInterface $client;

    /**
     * Constructor — selects the right client automatically
     */
    public function __construct() {
        $type = get_option('packshotphoto_connection_type', 'our_service');

        if ('custom_api' === $type) {
            $this->client = new OpenAIClient();
            Logger::debug('ApiRouter: Initialized with OpenAIClient (custom_api)');
        } else {
            $this->client = new CloudClient();
            Logger::debug('ApiRouter: Initialized with CloudClient (our_service)');
        }
    }

    /**
     * Test API connection
     *
     * @return array{success: bool, message: string}
     */
    public function test_connection(): array {
        return $this->client->test_connection();
    }

    /**
     * Generate SEO description for media file
     *
     * @param string $file_path Absolute path to file
     * @param string $mime_type MIME type
     * @param int    $post_id   Attachment ID
     * @param string $language  Optional target language override
     * @return array{success: bool, message?: string, data?: array}
     */
    public function generate_seo_description(string $file_path, string $mime_type, int $post_id = 0, string $language = '', string $image_context = ''): array {
        $limit = $this->check_rate_limit();
        if (!$limit['success']) {
            return $limit;
        }

        return $this->client->generate_seo_description($file_path, $mime_type, $post_id, $language, $image_context);
    }

    /**
     * Summarize site context from homepage text
     *
     * @param string $text     Homepage text content
     * @param string $language Optional target language override
     * @return array{success: bool, message?: string, data?: string}
     */
    public function summarize_site_context(string $text, string $language = ''): array {
        $limit = $this->check_rate_limit();
        if (!$limit['success']) {
            return $limit;
        }

        return $this->client->summarize_site_context($text, $language);
    }


    /**
     * Prevent too many requests to AI services
     *
     * @return array{success: bool, message?: string}
     */
    private function check_rate_limit(): array {
        $last_request = (int) get_option('packshotphoto_last_ai_request', 0);
        $now          = time();
        $cooldown     = 1;

        if ($now - $last_request < $cooldown) {
            Logger::info('Rate limit triggered for AI request', ['wait' => $cooldown - ($now - $last_request)]);
            return [
                'success' => false,
                'message' => __('Too many AI requests. Please wait a moment...', 'packshotphoto-ai'),
            ];
        }

        update_option('packshotphoto_last_ai_request', $now, false);
        return ['success' => true];
    }
}
