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

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\ImageProviderInterface;
use AutoMarketerAI\ImageProvider;

defined('ABSPATH') || exit;

final class ImgDalle implements ImageProviderInterface
{
    private const PREFIX        = 'sk-proj-';
    private const DEFAULT_MODEL = 'dall-e-3';
    private const API_BASE      = 'https://api.openai.com/v1';

    // Per-model cost strings shown on the card chip.
    private const MODEL_COSTS = [
        'dall-e-3' => '$0.04 / image',
        'dall-e-2' => '$0.02 / image',
    ];

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

    public function get_name(): string
    {
        return 'DALL-E 3';
    }

    public function get_description(): string
    {
        return 'OpenAI\'s image generation model. Produces high-quality, prompt-accurate visuals - ideal for marketing content and social posts.';
    }

    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 [
            'dall-e-3' => 'DALL-E 3 -- $0.04/image, best quality',
            'dall-e-2' => 'DALL-E 2 -- $0.02/image, fast & cheap',
        ];
    }

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

    // Fetch live DALL-E models from OpenAI, filtered to dall-e-* only.
    // 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();
        }

        $result = [];
        foreach ($body['data'] as $m) {
            $id = (string) ($m['id'] ?? '');
            if (!str_starts_with($id, 'dall-e-')) {
                continue;
            }
            $cost           = self::MODEL_COSTS[$id] ?? null;
            $cost_suffix    = $cost ? ' — ' . $cost : '';
            $result[$id]    = strtoupper(str_replace('-', ' ', $id)) . $cost_suffix;
        }

        // Sort: dall-e-3 before dall-e-2.
        krsort($result);

        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 [
            'dall-e-3' => 'OpenAI\'s DALL-E 3 generates high-quality, prompt-accurate marketing visuals. Uses your existing OpenAI API key.',
            'dall-e-2' => 'OpenAI\'s DALL-E 2 is a faster, lighter option for bulk image generation at lower cost. Uses your existing OpenAI API key.',
        ];
    }

    public function validate_api_key(string $key): bool
    {
        if (!str_starts_with($key, 'sk-')) {
            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 DALL-E 3.
    // 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,
            'size'            => '1024x1024',
            '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' => 60,
        ]);

        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-dalle');
    }
}