<?php
/**
 * Parameter Service - AI parameter optimization
 *
 * Fetches optimized AI parameters from remote API.
 * Supports OpenAI, Gemini, and OpenRouter providers.
 *
 * @package AIPT\Core\CreditSystem
 */

namespace AIPT\Core\CreditSystem;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Parameter Service
 */
class ParameterService
{
    private const API_URL = 'https://api.aiforwoo.com/api/v2/optimize/parameters';
    private const CACHE_TTL = 1800; 
    private const TIMEOUT = 10;

    /**
     * Default parameters per provider
     */
    private static array $defaults = [
        'openai' => [
            'temperature' => 0.7,
            'top_p' => 1.0,
            'frequency_penalty' => 0.0,
            'presence_penalty' => 0.0
        ],
        'gemini' => [
            'temperature' => 0.7,
            'top_p' => 0.95,
            'top_k' => 40
        ],
        'openrouter' => [
            'temperature' => 0.7,
            'top_p' => 1.0
        ]
    ];

    /**
     * Get optimized parameters for multiple types
     *
     * @param array $types Content types (description, title, tags, etc.)
     * @param string $provider AI provider (openai, gemini, openrouter)
     * @param string|null $model Optional model name
     * @return array Parameters by type
     */
    public function getParameters(array $types, string $provider = 'openai', ?string $model = null): array
    {
        $defaults = self::$defaults[$provider] ?? self::$defaults['openai'];

        if ($this->isFreePlan()) {
            return array_fill_keys($types, $defaults);
        }

        $cacheKey = $this->getCacheKey($provider, $model);
        $cached = get_transient($cacheKey);

        if ($cached !== false) {
            return $this->filterTypes($cached, $types, $defaults);
        }

        $fetched = $this->fetchFromApi($provider, $model);

        if ($fetched !== null) {
            set_transient($cacheKey, $fetched, self::CACHE_TTL);
            return $this->filterTypes($fetched, $types, $defaults);
        }

        return array_fill_keys($types, $defaults);
    }

    /**
     * Get parameters for single type
     *
     * @param string $type Content type
     * @param string $provider AI provider
     * @param string|null $model Optional model name
     * @return array Parameters
     */
    public function getForType(string $type, string $provider = 'openai', ?string $model = null): array
    {
        $result = $this->getParameters([$type], $provider, $model);
        return $result[$type] ?? self::$defaults[$provider] ?? self::$defaults['openai'];
    }

    /**
     * Get default parameters for provider
     *
     * @param string $provider AI provider
     * @return array Default parameters
     */
    public function getDefaults(string $provider = 'openai'): array
    {
        return self::$defaults[$provider] ?? self::$defaults['openai'];
    }

    /**
     * Clear parameter cache
     *
     * @param string|null $provider Optional provider to clear
     */
    public function clearCache(?string $provider = null): void
    {
        if ($provider !== null) {
            delete_transient($this->getCacheKey($provider, null));
        } else {
            foreach (array_keys(self::$defaults) as $p) {
                delete_transient($this->getCacheKey($p, null));
            }
        }
    }

    /**
     * Fetch parameters from API
     *
     * @param string $provider AI provider
     * @param string|null $model Model name
     * @return array|null Parameters or null on failure
     */
    private function fetchFromApi(string $provider, ?string $model): ?array
    {
        $response = wp_remote_post(self::API_URL, [
            'timeout' => self::TIMEOUT,
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ],
            'body' => wp_json_encode([
                'provider' => $provider,
                'model' => $model,
                'site_url' => get_site_url()
            ]),
            'sslverify' => true
        ]);

        if (is_wp_error($response)) {
            return null;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code >= 400) {
            return null;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (!is_array($data)) {
            return null;
        }

        if (!isset($data['parameters']) || !is_array($data['parameters'])) {
            return null;
        }

        return $data['parameters'];
    }

    /**
     * Filter parameters for requested types
     *
     * @param array $all All available parameters
     * @param array $types Requested types
     * @param array $defaults Default parameters
     * @return array Filtered parameters
     */
    private function filterTypes(array $all, array $types, array $defaults): array
    {
        $result = [];
        foreach ($types as $type) {
            $result[$type] = $all[$type] ?? $defaults;
        }
        return $result;
    }

    /**
     * Get cache key for parameters
     *
     * @param string $provider AI provider
     * @param string|null $model Model name
     * @return string Cache key
     */
    private function getCacheKey(string $provider, ?string $model): string
    {
        return 'aipt_params_' . md5($provider . ($model ?? ''));
    }

    /**
     * Check if current plan is free
     *
     * @return bool
     */
    private function isFreePlan(): bool
    {
        if (!function_exists('aipt_fs')) {
            return true;
        }

        return !aipt_fs()->is_paying();
    }
}
