<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/modules/img-aurora.php
// Description: Aurora (xAI) image provider module — NUCLEAR+++
// Last Edited: 2026-04-10
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\ImageProviderInterface;
use AutoMarketerAI\ImageProvider;

defined('ABSPATH') || exit;

final class ImgAurora implements ImageProviderInterface
{
    private const PREFIX        = 'xai-';
    private const DEFAULT_MODEL = 'aurora';
    private const API_BASE      = 'https://api.x.ai/v1';

    // Known xAI image models and their costs.
    // Aurora is the current flagship; grok-2-image-* is the legacy model.
    private const MODEL_COSTS = [
        'aurora'              => '$0.02 / image',
        'grok-2-image-1212'   => '$0.07 / image',
    ];

    public function get_id(): string
    {
        return 'img-aurora';
    }

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

    public function get_description(): string
    {
        return 'xAI\'s Aurora image model. Distinctive, vivid visuals built for creative and brand-forward social content.';
    }

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

    public function get_category(): string
    {
        return 'Image';
    }

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

    public function get_available_models(): array
    {
        return [
            'aurora'            => 'Aurora -- $0.02/image, recommended',
            'grok-2-image-1212' => 'Grok 2 Image -- $0.07/image, legacy',
        ];
    }

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

    // Fetch live image-capable models from xAI, filtered to known image models.
    // Falls back to get_available_models() on any error.
    public function fetch_live_models(string $key): array
    {
        $response = wp_remote_get(self::API_BASE . '/models', [
            'headers' => [
                'Authorization' => 'Bearer ' . $key,
                'Content-Type'  => 'application/json',
            ],
            'timeout' => 10,
        ]);

        if (is_wp_error($response) || (int) wp_remote_retrieve_response_code($response) !== 200) {
            return $this->get_available_models();
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!is_array($body) || empty($body['data'])) {
            return $this->get_available_models();
        }

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

        // Preserve MODEL_COSTS order — aurora first.
        foreach (self::MODEL_COSTS as $model_id => $cost) {
            if (!in_array($model_id, $live_ids, true)) {
                continue;
            }
            $label          = ucwords(str_replace(['-', '_'], ' ', $model_id));
            $result[$model_id] = $label . ' — ' . $cost;
        }

        return !empty($result) ? $result : $this->get_available_models();
    }

    // Returns per-model cost map for JS chip updates.
    public function get_model_costs(): array
    {
        return self::MODEL_COSTS;
    }

    public function get_model_descriptions(): array
    {
        return [
            'aurora'            => 'xAI\'s Aurora creates striking, stylized visuals with a distinct aesthetic. Uses your existing Grok API key.',
            'grok-2-image-1212' => 'xAI\'s Grok 2 Image is the legacy model - reliable for standard image generation tasks. Uses your existing Grok API key.',
        ];
    }

    public function validate_api_key(string $key): bool
    {
        if (!str_starts_with($key, self::PREFIX)) {
            return false;
        }

        $response = wp_remote_get(self::API_BASE . '/models', [
            'headers' => [
                'Authorization' => 'Bearer ' . $key,
                'Content-Type'  => 'application/json',
            ],
            'timeout' => 10,
        ]);

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

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

    public function register(): void
    {
        // No additional hooks needed — activation handled by AdminPage
    }

    public function get_api_key_prefix(): string
    {
        return self::PREFIX;
    }

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

    public function render_activation_popup(): void
    {
        // Not used — activation modal is rendered by the shared template
    }

    // --------------------------------------------------
    // Generate an image using xAI Aurora.
    // Returns a local WP attachment URL on success, null on failure.
    // --------------------------------------------------
    public function generate_raw(string $prompt, string $api_key = '', string $model = ''): string
    {
        return '';
    }

    public function generate_image(string $prompt, string $api_key): ?string
    {
        if ($prompt === '' || $api_key === '') {
            return null;
        }

        $safe_prompt = mb_substr($prompt, 0, 4000);

        $body = wp_json_encode([
            'model'           => self::DEFAULT_MODEL,
            'prompt'          => $safe_prompt,
            'n'               => 1,
            'response_format' => 'url',
        ]);

        if ($body === false) {
            return null;
        }

        $response = wp_remote_post(self::API_BASE . '/images/generations', [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ],
            'body'    => $body,
            'timeout' => 90,
        ]);

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

        $code = (int) wp_remote_retrieve_response_code($response);
        $json = json_decode(wp_remote_retrieve_body($response), true);

        if ($code !== 200 || !is_array($json) || empty($json['data'][0]['url'])) {
            return null;
        }

        $image_url = (string) $json['data'][0]['url'];

        return ImageProvider::downloadToMediaLibrary($image_url, 'amai-aurora');
    }
}