<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: modules/ai-openai.php
// Last Edited: 2026-05-19
// Description: OpenAI provider module — NUCLEAR+++
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\AbstractAiProvider;

if (!defined('ABSPATH')) {
    exit('Direct access forbidden.');
}

final class Openai extends AbstractAiProvider
{
    // Ordered allowlist of content-generation models to surface in the UI.
    // Add new OpenAI chat/text models here as they ship.
    private const MODEL_ALLOWLIST = [
        'gpt-5.5'      => 'GPT-5.5 — Latest flagship',
        'gpt-4.1'      => 'GPT-4.1 — Best coding & instruction',
        'gpt-4.1-mini' => 'GPT-4.1 Mini — Fast & cost-effective',
        'gpt-4o'       => 'GPT-4o — Multimodal, high quality',
        'gpt-4o-mini'  => 'GPT-4o Mini — Lightweight & fast',
    ];

    public function get_id(): string
    {
        return 'ai-openai';
    }

    public function get_name(): string
    {
        return 'OpenAI';
    }

    public function get_description(): string
    {
        return 'Powerful models for content creation, coding, analysis, and general tasks.';
    }

    public function get_logo_url(): string
    {
        return '';
    }

    public function get_model_count(): int
    {
        return count(self::MODEL_ALLOWLIST);
    }

    public function get_available_models(): array
    {
        return self::MODEL_ALLOWLIST;
    }

    public function get_model_descriptions(): array
    {
        return [
            'gpt-5.5'      => 'OpenAI\'s most capable model. Best for complex reasoning, nuanced writing, and demanding tasks.',
            'gpt-4.1'      => 'Excellent for coding and precise instruction-following. Strong all-around quality.',
            'gpt-4.1-mini' => 'Fast and cost-effective. A great default for most social media content tasks.',
            'gpt-4o'       => 'Multimodal flagship model. Strong reasoning and high-quality writing.',
            'gpt-4o-mini'  => 'Lightweight and fast. Best for high-volume or budget-conscious workloads.',
        ];
    }

    public function get_default_model(): string
    {
        return 'gpt-5.5';
    }

    public function get_api_key_prefix(): string
    {
        return 'sk-proj-';
    }

    // Fetch the live model list from OpenAI and intersect with the allowlist.
    // Returns allowlist models that the user's key actually has access to,
    // preserving the allowlist order. Falls back to full allowlist on error.
    public function fetch_live_models(string $key): array
    {
        $response = wp_remote_get('https://api.openai.com/v1/models', [
            'headers' => ['Authorization' => 'Bearer ' . $key],
            'timeout' => 10,
        ]);

        if (is_wp_error($response) || (int) wp_remote_retrieve_response_code($response) !== 200) {
            return self::MODEL_ALLOWLIST;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!is_array($body) || empty($body['data'])) {
            return self::MODEL_ALLOWLIST;
        }

        $live_ids = array_column($body['data'], 'id');
        $result   = [];

        foreach (self::MODEL_ALLOWLIST as $model_id => $label) {
            if (in_array($model_id, $live_ids, true)) {
                $result[$model_id] = $label;
            }
        }

        return !empty($result) ? $result : self::MODEL_ALLOWLIST;
    }

    public function validate_api_key(string $key): bool
    {
        if (!str_starts_with($key, 'sk-')) {
            return false;
        }

        $response = wp_remote_get('https://api.openai.com/v1/models', [
            'headers' => ['Authorization' => 'Bearer ' . $key],
            'timeout' => 10,
        ]);

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

        return (int) wp_remote_retrieve_response_code($response) === 200;
    }

    public function generate_raw(string $prompt, string $api_key, string $model, int $max_tokens = 64): string
    {
        if ($prompt === '' || $api_key === '' || $model === '') {
            return '';
        }

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ],
            'body'    => (string) json_encode([
                'model'      => $model,
                'max_tokens' => $max_tokens,
                'messages'   => [['role' => 'user', 'content' => $prompt]],
            ]),
            'timeout' => 15,
        ]);

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

        $http_code = (int) wp_remote_retrieve_response_code($response);
        if ($http_code !== 200) {
            if ($http_code === 401 || $http_code === 429) {
                set_transient('amai_provider_credit_warning', $this->get_id(), HOUR_IN_SECONDS);
            }
            return '';
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        return trim((string) ($body['choices'][0]['message']['content'] ?? ''));
    }

    protected function get_pricing_note(): string
    {
        return 'Very inexpensive - OpenAI API requires only a small deposit to start (covers a lot of usage).';
    }

    protected function get_signup_url(): string
    {
        return 'https://platform.openai.com/signup';
    }

    protected function get_signup_label(): string
    {
        return 'Get one in 5 minutes';
    }
}