<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: modules/ai-mistral.php
// Last Edited: 2026-04-21
// Description: Mistral AI provider module — NUCLEAR+++
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\AbstractAiProvider;

if (!defined('ABSPATH')) {
    exit('No direct script access allowed.');
}

final class Mistral extends AbstractAiProvider
{
    private const VALIDATION_MODEL = 'mistral-small-latest';
    private const DEFAULT_MODEL    = 'mistral-small-latest';

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

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

    public function get_description(): string
    {
        return 'Fast, affordable AI from Europe. Mistral delivers high-quality marketing copy with no monthly minimum - pay only for what you use.';
    }

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

    public function get_model_count(): int
    {
        return 3;
    }

    public function get_available_models(): array
    {
        return [
            'mistral-large-latest' => 'Mistral Large — Most capable',
            'mistral-small-latest' => 'Mistral Small — Best overall',
            'open-mistral-nemo'    => 'Mistral Nemo — Fast & efficient',
        ];
    }

    public function get_model_descriptions(): array
    {
        return [
            'mistral-large-latest' => 'Mistral\'s flagship model. Best for complex reasoning, nuanced writing, and long-context tasks.',
            'mistral-small-latest' => 'The best balance of speed and quality. Recommended for most marketing content generation.',
            'open-mistral-nemo'    => 'Fastest and most cost-efficient. Great for high-volume, straightforward content tasks.',
        ];
    }

    public function get_default_model(): string
    {
        return self::DEFAULT_MODEL;
    }

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

    public function validate_api_key(string $key): bool
    {
        if (strlen($key) < 32) {
            return false;
        }

        $response = wp_remote_post('https://api.mistral.ai/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $key,
                'Content-Type'  => 'application/json',
            ],
            'body'    => (string) json_encode([
                'model'      => self::VALIDATION_MODEL,
                'max_tokens' => 1,
                'messages'   => [['role' => 'user', 'content' => 'hi']],
            ]),
            'timeout' => 10,
        ]);

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

        $code = wp_remote_retrieve_response_code($response);
        return $code === 200 || $code === 400;
    }

    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.mistral.ai/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 'Mistral API is pay-as-you-go with no monthly minimum.';
    }

    protected function get_signup_url(): string
    {
        return 'https://console.mistral.ai/api-keys';
    }

    protected function get_signup_label(): string
    {
        return 'Get one at console.mistral.ai';
    }
}