<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-image-provider.php
// Description: Resolves the active image provider module and generates an image for a post - NUCLEAR+++
// Last Edited: 2026-04-09
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class ImageProvider
{
    // --------------------------------------------------
    // Resolve the active image provider module, call generate_image(),
    // and return a local WP attachment URL.
    // Returns null if no image provider is active, the key is missing,
    // or generation fails for any reason.
    // --------------------------------------------------
    public static function resolveForPost(string $prompt): ?string
    {
        // 1. Find active img-* module id
        $active = get_option('amai_active_modules', []);
        if (!is_array($active)) {
            $active = [];
        }

        $provider_id = null;
        foreach ($active as $module_id) {
            if (is_string($module_id) && str_starts_with($module_id, 'img-')) {
                $provider_id = $module_id;
                break;
            }
        }

        if ($provider_id === null) {
            return null;
        }

        // 2. Load the module file
        $module_file = AMAI_PLUGIN_DIR . '/modules/' . $provider_id . '.php';
        if (!is_file($module_file)) {
            return null;
        }

        require_once $module_file;

        // 3. Resolve class name — mirrors load_modules() logic in AdminPage
        $basename = $provider_id; // e.g. 'img-dalle'
        $clean    = 'Img' . ucfirst(str_replace('-', '', substr($basename, 4))); // 'Imgdalle'
        $class    = '\\AutoMarketerAI\\Modules\\' . $clean;

        if (
            !class_exists($class) ||
            !is_subclass_of($class, '\\AutoMarketerAI\\ImageProviderInterface')
        ) {
            return null;
        }

        // 4. Retrieve and decrypt API key
        $stored_key = (string) get_option('amai_api_key_' . $provider_id, '');
        if ($stored_key === '') {
            return null;
        }

        $api_key = KeyVault::decrypt($stored_key);
        if ($api_key === '') {
            return null;
        }

        // 5. Call generate_image()
        /** @var ImageProviderInterface $provider */
        $provider = new $class();

        return $provider->generate_image($prompt, $api_key);
    }

    // --------------------------------------------------
    // Download a remote image URL to the WP media library.
    // Returns the attachment URL on success, null on failure.
    // Shared utility for all image provider implementations.
    // --------------------------------------------------
    public static function downloadToMediaLibrary(string $image_url, string $filename_prefix = 'amai-ai'): ?string
    {
        // Require WP file utilities
        if (!function_exists('download_url')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        if (!function_exists('media_handle_sideload')) {
            require_once ABSPATH . 'wp-admin/includes/media.php';
            require_once ABSPATH . 'wp-admin/includes/image.php';
        }

        $tmp = download_url($image_url, 30);
        if (is_wp_error($tmp)) {
            return null;
        }

        $ext = 'jpg';
        // Attempt to detect extension from URL
        $url_path = (string) parse_url($image_url, PHP_URL_PATH);
        if ($url_path !== '') {
            $detected = strtolower(pathinfo($url_path, PATHINFO_EXTENSION));
            if (in_array($detected, ['jpg', 'jpeg', 'png', 'webp'], true)) {
                $ext = $detected === 'jpeg' ? 'jpg' : $detected;
            }
        }

        $file_array = [
            'name'     => $filename_prefix . '-' . gmdate('YmdHis') . '.' . $ext,
            'tmp_name' => $tmp,
        ];

        $attachment_id = media_handle_sideload($file_array, 0, '');

        // Clean up tmp file if sideload failed
        if (is_wp_error($attachment_id)) {
            if (is_file($tmp)) {
                @unlink($tmp); // phpcs:ignore — WP core pattern for tmp cleanup
            }
            return null;
        }

        $url = (string) wp_get_attachment_url($attachment_id);
        return $url !== '' ? $url : null;
    }

    // --------------------------------------------------
    // Save raw image bytes to the WP media library.
    // Used by providers that return base64-encoded image data
    // rather than a URL (e.g. Imagen 3).
    // Returns the attachment URL on success, null on failure.
    // --------------------------------------------------
    public static function saveBytesToMediaLibrary(string $bytes, string $ext = 'png', string $filename_prefix = 'amai-ai'): ?string
    {
        if (!function_exists('media_handle_sideload')) {
            require_once ABSPATH . 'wp-admin/includes/media.php';
            require_once ABSPATH . 'wp-admin/includes/image.php';
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        $tmp = wp_tempnam($filename_prefix . '.' . $ext);
        if ($tmp === false || $tmp === '') {
            return null;
        }

        $written = file_put_contents($tmp, $bytes);
        if ($written === false || $written === 0) {
            if (is_file($tmp)) {
                @unlink($tmp);
            }
            return null;
        }

        $file_array = [
            'name'     => $filename_prefix . '-' . gmdate('YmdHis') . '.' . $ext,
            'tmp_name' => $tmp,
        ];

        $attachment_id = media_handle_sideload($file_array, 0, '');

        if (is_wp_error($attachment_id)) {
            if (is_file($tmp)) {
                @unlink($tmp);
            }
            return null;
        }

        $url = (string) wp_get_attachment_url($attachment_id);
        return $url !== '' ? $url : null;
    }
}