<?php

namespace App\Support;

use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;

/**
 * The small amount of Markdown a chat reply actually uses.
 *
 * Models write lists, bold and the occasional link, and rendering that as plain
 * text turns a readable answer into a wall of hyphens and asterisks.
 *
 * Deliberately not a full Markdown library. The input is model output rendered
 * straight into the page, so everything is escaped first and only a fixed set of
 * patterns is turned back into markup. A general parser would be a larger
 * surface for very little gain here.
 */
class Markdown
{
    public static function toHtml(?string $text, bool $tables = false): HtmlString
    {
        $marked = self::inline(e(trim((string) $text)));

        if ($tables) {
            $marked = self::tables($marked);
        }

        return new HtmlString(self::paragraphs($marked));
    }

    /** Bold, italic, inline code and links. */
    private static function inline(string $text): string
    {
        $patterns = [
            '/`([^`]+)`/' => '<code>$1</code>',
            '/\*\*([^*]+)\*\*/' => '<strong>$1</strong>',
            '/(?<![\w*])\*([^*\n]+)\*(?![\w*])/' => '<em>$1</em>',
            '/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/' => '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>',
        ];

        $text = preg_replace(array_keys($patterns), array_values($patterns), $text);

        // Bare URLs, but not ones already inside an anchor from the step above.
        return preg_replace(
            '/(?<!href=")(?<!">)(https?:\/\/[^\s<]+)/',
            '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
            $text,
        );
    }

    /**
     * Blocks: bulleted lists, numbered lists, and everything else as paragraphs.
     *
     * Models mix "-", "*", "1." and "1)" freely, so all four are treated as list
     * markers rather than left as literal characters.
     *
     * The split is UTF-8. Without /u, \R treats the single byte 0x85 as a line
     * break, and that byte is the end of ✕ (U+2715). Cutting it there leaves an
     * orphaned prefix that is not valid UTF-8, and the chat cannot encode the
     * reply as JSON.
     */
    private static function paragraphs(string $text): string
    {
        $html = '';
        $list = null;

        foreach (preg_split('/\R/u', $text) as $line) {
            $line = rtrim($line);

            if (trim($line) === '') {
                $html .= self::closeList($list);

                continue;
            }

            if (preg_match('/^\s*[-*]\s+(.*)$/u', $line, $matches)) {
                $html .= self::openList($list, 'ul');
                $html .= '<li>'.$matches[1].'</li>';

                continue;
            }

            if (preg_match('/^\s*\d+[.)]\s+(.*)$/u', $line, $matches)) {
                $html .= self::openList($list, 'ol');
                $html .= '<li>'.$matches[1].'</li>';

                continue;
            }

            $html .= self::closeList($list);

            if (preg_match('/^\s*#{1,6}\s+(.+)$/u', $line, $matches) === 1) {
                $title = $matches[1];

                if (! str_starts_with($title, '<strong>')) {
                    $title = '<strong>'.$title.'</strong>';
                }

                $html .= '<p>'.$title.'</p>';

                continue;
            }

            if (str_starts_with($line, '<div class="mb-chat-table-wrap">')) {
                $html .= $line;

                continue;
            }

            $html .= '<p>'.$line.'</p>';
        }

        return $html.self::closeList($list);
    }

    private static function openList(?string &$list, string $tag): string
    {
        if ($list === $tag) {
            return '';
        }

        $html = self::closeList($list);
        $list = $tag;

        return $html."<{$tag}>";
    }

    private static function closeList(?string &$list): string
    {
        if ($list === null) {
            return '';
        }

        $html = "</{$list}>";
        $list = null;

        return $html;
    }

    private static function tables(string $text): string
    {
        $lines = preg_split('/\R/u', $text) ?: [];
        $output = [];
        $index = 0;
        $count = count($lines);

        while ($index < $count) {
            $next = $lines[$index + 1] ?? null;

            if (self::isTableRow($lines[$index]) && is_string($next) && self::isSeparator($next)) {
                $header = self::cells($lines[$index]);
                $index += 2;
                $body = [];

                while ($index < $count && self::isTableRow($lines[$index]) && ! self::isSeparator($lines[$index])) {
                    $body[] = self::cells($lines[$index]);
                    $index++;
                }

                $output[] = self::table($header, $body);

                continue;
            }

            $output[] = $lines[$index];
            $index++;
        }

        return implode("\n", $output);
    }

    private static function isTableRow(string $line): bool
    {
        return str_contains($line, '|');
    }

    private static function isSeparator(string $line): bool
    {
        return preg_match('/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/', trim($line)) === 1;
    }

    /**
     * A pipe inside a cell is written as \|. That must stay in the cell.
     * Campaign names such as "101|New Electric IX SUVs 2025_US_M_MK" otherwise
     * become an extra column and shift Campaign ID, platform, and spend.
     *
     * @return list<string>
     */
    private static function cells(string $line): array
    {
        $line = trim($line);

        if (str_starts_with($line, '|')) {
            $line = substr($line, 1);
        }

        if (str_ends_with($line, '|') && ! str_ends_with($line, '\\|')) {
            $line = substr($line, 0, -1);
        }

        $cells = [];
        $current = '';
        $length = strlen($line);

        for ($i = 0; $i < $length; $i++) {
            if ($line[$i] === '\\' && ($line[$i + 1] ?? '') === '|') {
                $current .= '|';
                $i++;

                continue;
            }

            if ($line[$i] === '|') {
                $cells[] = trim($current);
                $current = '';

                continue;
            }

            $current .= $line[$i];
        }

        $cells[] = trim($current);

        return $cells;
    }

    /**
     * @param  list<string>  $header
     * @param  list<list<string>>  $body
     */
    private static function table(array $header, array $body): string
    {
        $class = 'mb-chat-table';
        $stats = count($header) === 2 && strcasecmp($header[0], 'Stat') === 0 && strcasecmp($header[1], 'Value') === 0;

        if ($stats) {
            $class .= ' mb-chat-stats';
            $paired = [];

            for ($index = 0, $count = count($body); $index < $count; $index += 2) {
                $left = $body[$index];
                $right = $body[$index + 1] ?? ['', ''];
                $paired[] = [$left[0] ?? '', $left[1] ?? '', $right[0] ?? '', $right[1] ?? ''];
            }

            $header = ['Stat', 'Value', 'Stat', 'Value'];
            $body = $paired;
        }

        $html = '<div class="mb-chat-table-wrap"><table class="'.$class.'">';

        if (! $stats) {
            $html .= '<thead><tr>';

            foreach ($header as $cell) {
                $html .= '<th>'.$cell.'</th>';
            }

            $html .= '</tr></thead>';
        }

        $html .= '<tbody>';

        foreach ($body as $row) {
            $html .= '<tr>';

            for ($index = 0, $width = count($header); $index < $width; $index++) {
                $cell = $row[$index] ?? '';
                $label = $stats && $index % 2 === 0;

                if ($label && $cell !== '') {
                    $cell = '<strong>'.$cell.'</strong>';
                }

                $html .= '<td'.($label ? ' class="mb-chat-stat-label"' : '').'>'.$cell.'</td>';
            }

            $html .= '</tr>';
        }

        return $html.'</tbody></table></div>';
    }

    /** A short single line, for places that cannot take block markup. */
    public static function toLine(?string $text): string
    {
        return Str::of((string) $text)->replaceMatches('/\s+/', ' ')->trim()->toString();
    }
}
