<?php
/**
 * AI Processor — Shared logic for AI SEO generation
 *
 * Eliminates duplication between QueueManager, BulkActions, and InlineEditor.
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\Core;

use PackshotPhotoAI\API\ApiRouter;

defined('ABSPATH') || exit;

class AIProcessor {

    public static function generate(int $post_id, string $image_context = ''): array {
        $file_path = get_attached_file($post_id);
        $mime_type = get_post_mime_type($post_id);

        if (!$file_path || !file_exists($file_path)) {
            return ['success' => false, 'message' => 'File not found'];
        }

        if (strpos($mime_type, 'image/') !== 0) {
            return ['success' => false, 'message' => 'Not an image'];
        }

        if (!CreditManager::has_credits()) {
            return ['success' => false, 'message' => 'Insufficient credits'];
        }

        $client = new ApiRouter();
        $result = $client->generate_seo_description($file_path, $mime_type, $post_id, '', $image_context);

        if (!$result['success']) {
            return $result;
        }

        CreditManager::deduct_credit(1);

        $data = $result['data'];

        // Always backup current values before AI overwrites them
        $backup = [
            'alt'         => get_post_meta($post_id, '_wp_attachment_image_alt', true) ?: '',
            'caption'     => '',
            'description' => '',
        ];
        $existing_post = get_post($post_id);
        if ($existing_post) {
            $backup['caption'] = $existing_post->post_excerpt ?: '';
            $backup['description'] = $existing_post->post_content ?: '';
        }
        $original_filename = get_post_meta($post_id, '_pmm_original_filename', true);
        if ($original_filename) {
            $backup['original_filename'] = $original_filename;
        }
        update_post_meta($post_id, '_pmm_ai_backup', $backup);

        if (!empty($data['alt'])) {
            update_post_meta($post_id, '_wp_attachment_image_alt', sanitize_text_field($data['alt']));
        }

        $update_args = ['ID' => $post_id];

        if (!empty($data['caption'])) {
            $update_args['post_excerpt'] = wp_kses_post($data['caption']);
        }

        if (!empty($data['desc'])) {
            $update_args['post_content'] = wp_kses_post($data['desc']);
        }

        if (!empty($data['slug'])) {
            $settings = get_option('packshotphoto_settings', []);
            if ($settings['sync_slug'] ?? true) {
                $update_args['post_name'] = sanitize_title($data['slug']);
            }
        }

        if (count($update_args) > 1) {
            wp_update_post($update_args);
        }

        // Save opener to recent memory (prevents repetitive description openings)
        if (!empty($data['desc'])) {
            $openers   = (array) get_option('packshotphoto_recent_openers', []);
            $openers[] = implode(' ', array_slice(explode(' ', $data['desc']), 0, 8));
            update_option('packshotphoto_recent_openers', array_slice($openers, -30), false);
        }

        return ['success' => true, 'message' => 'AI generated', 'data' => $data];
    }
}
