<?php
namespace EasyChat\Library\Messenger;

 
final class SmsTextMetrics {
    public const MAX_SEGMENTS = 4;

    public static function segments(string $text): int {
        if ($text === '') return 0;
         
         
        $gsm_basic = "@£\$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\033ÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑÜ§¿abcdefghijklmnopqrstuvwxyzäöñüà";
        $gsm_extended = "\f^{}\\[~]|€";
        $basic_lookup = array_fill_keys(preg_split('//u', $gsm_basic, -1, PREG_SPLIT_NO_EMPTY) ?: [], true);
        $extended_lookup = array_fill_keys(preg_split('//u', $gsm_extended, -1, PREG_SPLIT_NO_EMPTY) ?: [], true);
        $septets = 0;
        $characters = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
        if (!is_array($characters)) return self::MAX_SEGMENTS + 1;
        foreach ($characters as $char) {
            if (isset($basic_lookup[$char])) {
                $septets++;
            } elseif (isset($extended_lookup[$char])) {
                $septets += 2;
            } else {
                $septets = -1;
                break;
            }
        }
        if ($septets >= 0) return $septets <= 160 ? 1 : (int)ceil($septets / 153);

        $units = 0;
        foreach ($characters as $char) {
            $units += (ord($char[0]) & 0xF8) === 0xF0 ? 2 : 1;
        }
        return $units <= 70 ? 1 : (int)ceil($units / 67);
    }

    public static function accepts(string $text): bool {
        return self::segments($text) <= self::MAX_SEGMENTS;
    }
}
