<?php

namespace AIPT\Utils;

/**
 * Utility class for masking and restoring image tags in HTML content.
 *
 * @since 2.5.13
 */
class ImagePreserver {

    /**
     * Extract all <img> tags from HTML, replacing each with a unique placeholder.
     *
     * @param string $content Raw HTML content (may contain zero or more <img> tags).
     * @param int    $startIndex Starting index for placeholder numbering.
     * @return array{content: string, imageMap: array<string, string>} HTML with placeholders and image map.
     *
     * @since 2.5.13
     */
    public static function mask( string $content, int $startIndex = 0 ): array {
        $imageMap = array();
        $counter  = $startIndex;

        $maskedContent = preg_replace_callback(
            '/<img\b[^>]*\/?>/is',
            function ( $matches ) use ( &$imageMap, &$counter ) {
                $placeholder               = '##AIPT_IMG_' . $counter . '##';
                $imageMap[ $placeholder ] = $matches[0];
                $counter++;

                return $placeholder;
            },
            $content
        );

        if ( null === $maskedContent ) {
            return array(
                'content'  => $content,
                'imageMap' => array(),
            );
        }

        return array(
            'content'  => $maskedContent,
            'imageMap' => $imageMap,
        );
    }

    /**
     * Restore <img> tags from placeholders. Handles dropped placeholders via fallback append.
     *
     * @param string                $content AI response content containing placeholders.
     * @param array<string, string> $imageMap Placeholder => <img> tag map from mask().
     * @return array{content: string, restored: int, missing: array<int, string>} Restored content metadata.
     *
     * @since 2.5.13
     */
    public static function unmask( string $content, array $imageMap ): array {
        $restored = 0;
        $missing  = array();

        foreach ( $imageMap as $placeholder => $imageTag ) {
            if ( false !== strpos( $content, $placeholder ) ) {
                $content = str_replace( $placeholder, $imageTag, $content );
                $restored++;
                continue;
            }

            $missing[] = $placeholder;
        }

        if ( ! empty( $missing ) ) {
            $missingImages = array();

            foreach ( $missing as $placeholder ) {
                if ( isset( $imageMap[ $placeholder ] ) ) {
                    $missingImages[] = $imageMap[ $placeholder ];
                }
            }

            $content .= "\n\n<p>\n" . implode( "\n", $missingImages ) . "\n</p>";
        }

        return array(
            'content'  => $content,
            'restored' => $restored,
            'missing'  => $missing,
        );
    }
}
