<?php
namespace EasyChat\Library\Messenger;

use EasyChat\Library\MessageTextRenderer;






class OutboundTextFormatter {

    public static function forProvider(string $provider, string $text): array {
        $provider = strtolower(trim($provider));
        if (strpos($text, '](') === false) {
            return array('text' => $text, 'format' => 'plain');
        }

        if ($provider === 'max' || $provider === 'max_bot') {
            return array('text' => self::renderLinks($text, 'markdown'), 'format' => 'markdown');
        }
        if ($provider === 'telegram') {
            return array('text' => self::renderLinks($text, 'html'), 'format' => 'html');
        }
        return array('text' => self::renderLinks($text, 'plain'), 'format' => 'plain');
    }

    private static function renderLinks(string $text, string $mode): string {
        $pattern = '/\[([^\]\r\n]{1,300})\]\(([^\s<>"\'\r\n]{1,2048})\)/u';
        $offset = 0;
        $output = '';
        if (!preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE)) {
            return $mode === 'html' ? htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') : $text;
        }

        foreach ($matches[0] as $index => $match) {
            $full = (string)$match[0];
            $position = (int)$match[1];
            $label = (string)$matches[1][$index][0];
            $url = (string)$matches[2][$index][0];
            $prefix = substr($text, $offset, $position - $offset);
            $output .= $mode === 'html'
                ? htmlspecialchars($prefix, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
                : $prefix;

            $clean_label = str_replace(array('\\[', '\\]'), array('[', ']'), $label);
            if (!MessageTextRenderer::isSafeHttpUrl($url)) {
                $output .= $mode === 'html'
                    ? htmlspecialchars($clean_label, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
                    : $clean_label;
            } elseif ($mode === 'html') {
                $output .= '<a href="' . htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">'
                    . htmlspecialchars($clean_label, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
                    . '</a>';
            } elseif ($mode === 'markdown') {
                $output .= '[' . str_replace(array('\\', '[', ']'), array('\\\\', '\\[', '\\]'), $clean_label) . '](' . $url . ')';
            } else {
                $output .= $clean_label . ': ' . $url;
            }
            $offset = $position + strlen($full);
        }
        $tail = substr($text, $offset);
        $output .= $mode === 'html'
            ? htmlspecialchars($tail, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
            : $tail;
        return $output;
    }
}
