<?php

/**
 * Reads attachment context and writes/reverts alt text with undo tracking.
 *
 * @package BulkAltText
 */

declare(strict_types=1);

namespace BulkAltText\Media;

if (!defined('ABSPATH')) {
    exit;
}

class AltWriter
{
    public const ALT_META  = '_wp_attachment_image_alt';
    public const PREV_META = '_batai_prev_alt';
    public const FLAG_META = '_batai_generated';

    /**
     * Apply generated alt text to an attachment, preserving any prior value so
     * it can be restored later.
     */
    public static function apply(int $attachmentId, string $text): void
    {
        $existing = (string) get_post_meta($attachmentId, self::ALT_META, true);

        // Only record the very first original, and only if we haven't before.
        if ($existing !== '' && get_post_meta($attachmentId, self::PREV_META, true) === '') {
            update_post_meta($attachmentId, self::PREV_META, $existing);
        }

        update_post_meta($attachmentId, self::ALT_META, $text);
        update_post_meta($attachmentId, self::FLAG_META, time());
    }

    /**
     * Restore the original alt text for one attachment we generated for.
     *
     * @return bool True if the attachment was one we had generated.
     */
    public static function revert(int $attachmentId): bool
    {
        if (get_post_meta($attachmentId, self::FLAG_META, true) === '') {
            return false;
        }

        $prev = get_post_meta($attachmentId, self::PREV_META, true);
        if ($prev !== '') {
            update_post_meta($attachmentId, self::ALT_META, $prev);
        } else {
            delete_post_meta($attachmentId, self::ALT_META);
        }

        delete_post_meta($attachmentId, self::PREV_META);
        delete_post_meta($attachmentId, self::FLAG_META);

        return true;
    }

    /**
     * How many attachments currently carry an AI-generated alt text.
     */
    public static function generated_count(): int
    {
        $q = new \WP_Query([
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'post_mime_type' => 'image',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'meta_key'       => self::FLAG_META, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        ]);

        return (int) $q->found_posts;
    }

    /**
     * Build the textual context we feed to the model for one attachment.
     *
     * @return array{filename:string,title:string,caption:string,context:string}
     */
    public static function context(int $attachmentId): array
    {
        $file    = get_attached_file($attachmentId);
        $caption = wp_get_attachment_caption($attachmentId);
        $parent  = (int) get_post_field('post_parent', $attachmentId);
        $context = '';

        if ($parent > 0) {
            $parentPost = get_post($parent);
            if ($parentPost) {
                $context = $parentPost->post_title . '. ' . wp_strip_all_tags($parentPost->post_content);
            }
        }

        return [
            'filename' => $file ? basename($file) : '',
            'title'    => (string) get_the_title($attachmentId),
            'caption'  => is_string($caption) ? $caption : '',
            'context'  => $context,
        ];
    }
}
