<?php

namespace App\Helpers;

use League\HTMLToMarkdown\HtmlConverter;

class MigrationHelpers
{

    public static function wpAutoP(string $content): string
    {
        $content = trim($content);
        if ($content === '') {
            return '';
        }

        $content = str_replace(["\r\n", "\r"], "\n", $content);
        $blocks = preg_split('/\n\s*\n/', $content);

        $blocks = array_map(function ($block) {
            $block = trim($block);
            if ($block === '') {
                return '';
            }
            if (preg_match('/^<(p|div|table|ul|ol|blockquote|h[1-6]|pre|figure)[\s>]/i', $block)) {
                return $block;
            }
            return '<p>' . nl2br($block, false) . '</p>';
        }, $blocks);

        return implode("\n\n", array_filter($blocks, fn ($b) => $b !== ''));
    }

    public static function htmlToMarkdown( ?string $html ): string
    {
        if (!$html || trim($html) === '') {
            return $html;
        }

        static $converter = null;
        if ($converter === null) {
            $converter = new HtmlConverter(['hard_break' => true]);
        }

        return $converter->convert(self::wpAutoP($html));
    }
}
