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

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\ImageProviderInterface;
use AutoMarketerAI\ImageProvider;

defined('ABSPATH') || exit;

final class ImgImagen implements ImageProviderInterface
{
    private const PREFIX        = 'AIzaSy';
    private const DEFAULT_MODEL = 'imagen-4.0-generate-001';

    // Per-model cost strings shown on the card chip.
    private const MODEL_COSTS = [
        'imagen-4.0-generate-001'       => '$0.04 / image',
        'imagen-4.0-ultra-generate-001' => '$0.06 / image',
        'imagen-4.0-fast-generate-001'  => '$0.02 / image',
        'imagen-3.0-generate-002'       => '$0.02 / image',
        'imagen-3.0-fast-generate-001'  => '$0.01 / image',
    ];

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

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

    public function get_description(): string
    {
        return 'Google\'s Imagen model. State-of-the-art photorealistic image generation with exceptional prompt adherence.';
    }

    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 [
            'imagen-4.0-generate-001'       => 'Imagen 4 -- $0.04/image, best quality',
            'imagen-4.0-ultra-generate-001' => 'Imagen 4 Ultra -- $0.06/image, highest quality',
            'imagen-4.0-fast-generate-001'  => 'Imagen 4 Fast -- $0.02/image, faster',
            'imagen-3.0-generate-002'       => 'Imagen 3 -- $0.02/image',
            'imagen-3.0-fast-generate-001'  => 'Imagen 3 Fast -- $0.01/image',
        ];
    }

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

    // Fetch live Imagen models from Google, filtered to imagen-* only.
    // Falls back to get_available_models() on any error.
    public function fetch_live_models(string $key): array
    {
        $url      = 'https://generativelanguage.googleapis.com/v1beta/models?key=' . rawurlencode($key);
        $response = wp_remote_get($url, ['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['models'])) {
            return $this->get_available_models();
        }

        $result = [];
        foreach ($body['models'] as $m) {
            if (!isset($m['name'])) {
                continue;
            }
            $id = str_replace('models/', '', (string) $m['name']);

            if (!str_starts_with($id, 'imagen-')) {
                continue;
            }

            // Only include models that support image prediction.
            $methods = $m['supportedGenerationMethods'] ?? [];
            if (!in_array('predict', $methods, true)) {
                continue;
            }

            $cost        = self::MODEL_COSTS[$id] ?? null;
            $display     = $m['displayName'] ?? $id;
            $cost_suffix = $cost ? ' — ' . $cost : '';
            $result[$id] = $display . $cost_suffix;
        }

        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 [
            'imagen-4.0-generate-001'       => 'Google\'s Imagen 4 produces photorealistic images with significantly improved detail and prompt accuracy. Uses your existing Google AI API key.',
            'imagen-4.0-ultra-generate-001' => 'Google\'s Imagen 4 Ultra delivers the highest quality photorealistic images available. Uses your existing Google AI API key.',
            'imagen-4.0-fast-generate-001'  => 'Google\'s Imagen 4 Fast delivers quality visuals at higher speed and lower cost. Uses your existing Google AI API key.',
            'imagen-3.0-generate-002'       => 'Google\'s Imagen 3 produces photorealistic images with exceptional detail. Uses your existing Google AI API key.',
            'imagen-3.0-fast-generate-001'  => 'Google\'s Imagen 3 Fast delivers quality visuals at higher speed and lower cost. Uses your existing Google AI API key.',
        ];
    }

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

        $url      = 'https://generativelanguage.googleapis.com/v1beta/models?key=' . rawurlencode($key);
        $response = wp_remote_get($url, ['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
    }

    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, 2000);
        $active_model = (string) get_option('amai_model_img-imagen', self::DEFAULT_MODEL);
        $endpoint     = 'https://generativelanguage.googleapis.com/v1beta/models/'
            . $active_model
            . ':predict?key='
            . rawurlencode($api_key);

        $body = wp_json_encode([
            'instances'  => [
                ['prompt' => $safe_prompt],
            ],
            'parameters' => [
                'sampleCount' => 1,
            ],
        ]);

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

        $response = wp_remote_post($endpoint, [
            'headers' => ['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)) {
            return null;
        }

        $b64 = $json['predictions'][0]['bytesBase64Encoded'] ?? '';
        if (!is_string($b64) || $b64 === '') {
            return null;
        }

        $bytes = base64_decode($b64, true);
        if ($bytes === false || $bytes === '') {
            return null;
        }

        $mime = (string) ($json['predictions'][0]['mimeType'] ?? 'image/png');
        $ext  = $mime === 'image/jpeg' ? 'jpg' : 'png';

        return ImageProvider::saveBytesToMediaLibrary($bytes, $ext, 'amai-imagen');
    }
}