<?php
/**
 * Persists AI [DOCUMENT] sections into WordPress posts created via AI.
 *
 * @package FleekDash\Controllers\AI
 * @since 2.3.0
 */

namespace FleekDash\Controllers\AI;

defined('ABSPATH') || exit;

/**
 * Markdown load + post update for AI document flow.
 */
final class AIChatDocumentPersistence
{
    /**
     * If $content contains a [DOCUMENT] block, convert it and save to the post matching $documentMetaId.
     */
    public function persistIfDocumentSectionPresent(string $documentMetaId, string $content): void
    {
        $docSection = $this->extractDocumentSection($content);
        if ($docSection === null || $docSection === '') {
            return;
        }

        $this->ensureMarkdownHelperLoaded();

        $contentWithoutTitle = $this->removeTitleFromContent($docSection);

        if (function_exists('fleekdash_markdown_to_html')) {
            $html = fleekdash_markdown_to_html($contentWithoutTitle);
        } else {
            error_log('[AIChatController] fleekdash_markdown_to_html function not found, using content as-is');
            $html = $contentWithoutTitle;
        }

        $this->updateDocumentByMetaId($documentMetaId, $html);
    }

    private function ensureMarkdownHelperLoaded(): void
    {
        if (function_exists('fleekdash_markdown_to_html')) {
            return;
        }

        $possible_paths = [
            defined('FLEEKDASH_PLUGIN_DIR') ? FLEEKDASH_PLUGIN_DIR . 'includes/Utils/Markdown.php' : null,
            __DIR__ . '/../../Utils/Markdown.php',
        ];

        foreach ($possible_paths as $util) {
            if ($util && file_exists($util)) {
                require_once $util;
                break;
            }
        }
    }

    private function extractDocumentSection(string $text): ?string
    {
        if ($text === '') {
            return null;
        }

        if (preg_match('/\[DOCUMENT\](.*?)\[\/DOCUMENT\]/s', $text, $m)) {
            $doc = trim($m[1] ?? '');

            return $doc !== '' ? $doc : null;
        }

        return null;
    }

    private function updateDocumentByMetaId(string $documentMetaId, string $htmlContent): void
    {
        $metaOk = $documentMetaId !== '' && $htmlContent !== '' && strpos($documentMetaId, 'doc_') === 0;
        if (!$metaOk) {
            return;
        }

        $posts = \get_posts([
            'post_type' => 'any',
            'post_status' => 'any',
            'numberposts' => 1,
            'meta_key' => 'document_id',
            'meta_value' => $documentMetaId,
            'fields' => 'ids',
        ]);

        $postId = (\is_array($posts) && isset($posts[0])) ? (int) $posts[0] : 0;
        if ($postId <= 0) {
            return;
        }

        $created_via_ai = \get_post_meta($postId, 'created_via_ai', true);
        if (!$created_via_ai) {
            if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
                error_log('FleekDash: Attempted to update post ' . $postId . ' via AI, but post was not created by AI');
            }

            return;
        }

        $update = [
            'ID' => $postId,
            'post_content' => $htmlContent,
            'meta_input' => [
                'updated_via_ai' => true,
                'updated_at' => \current_time('mysql'),
            ],
        ];

        $result = \wp_update_post($update, true);
        if (\is_wp_error($result) && defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
            error_log('FleekDash: Failed to update AI document: ' . $result->get_error_message());
        }
    }

    private function removeTitleFromContent(string $markdownContent): string
    {
        $content = preg_replace('/^#\s+.+$/m', '', $markdownContent, 1);
        $content = trim($content);

        return preg_replace('/^\s*\n+/', '', $content);
    }
}
