<?php
namespace EasyChat\Library\Ai;

class AvitoReplyTextNormalizer {
    public static function normalize(string $text): string {
        $text = trim($text);
        if ($text === '') {
            return '';
        }

        $text = self::expandCompactSpecs($text);
        $text = self::removeUnsupportedSeparatePartsClaims($text);
        $text = self::normalizeWhitespace($text);

        return trim((string)$text);
    }

    private static function expandCompactSpecs(string $text): string {
        $text = preg_replace('/\b(\d{1,3})\s*\/\s*(\d{2,4})\s*(?:gb|гб)?\s*(?:памяти|memory)?\b/iu', '$1 ГБ ОЗУ и $2 ГБ накопитель', $text);
        $text = preg_replace('/\b(\d{1,3})\s*(?:gb|гб)\s*\/\s*(\d+(?:[.,]\d+)?)\s*(tb|тб)\b/iu', '$1 ГБ ОЗУ и $2 ТБ накопитель', (string)$text);
        $text = preg_replace('/\b(\d{1,3})\s*(?:gb|гб)\s*\/\s*(\d{2,4})\s*(?:gb|гб)\b/iu', '$1 ГБ ОЗУ и $2 ГБ накопитель', (string)$text);

        return (string)$text;
    }

    private static function removeUnsupportedSeparatePartsClaims(string $text): string {
        $parts_words = '(?:комплектующ\w*|памят\w*|оперативн\w*\s+памят\w*|накопител\w*|детал\w*|запчаст\w*)';
        $not_sold = '(?:не\s+прода(?:ются|ём|ем|ю|ется)|не\s+реализ(?:уются|уем|ую|уется))';
        $patterns = [
            '/(?:^|(?<=[.!?])\s*)[^.!?]*(?:отдельно\s+)?' . $parts_words . '[^.!?]*' . $not_sold . '[^.!?]*[.!?]?/iu',
            '/(?:^|(?<=[.!?])\s*)[^.!?]*' . $not_sold . '[^.!?]*(?:отдельно\s+)?' . $parts_words . '[^.!?]*[.!?]?/iu',
            '/(?:^|(?<=[.!?])\s*)[^.!?]*(?:parts|components|ram|storage)[^.!?]*(?:not\s+sold|not\s+available)\s+separately[^.!?]*[.!?]?/iu',
        ];
        foreach ($patterns as $pattern) {
            $text = preg_replace($pattern, ' ', $text);
        }

        return trim((string)$text);
    }

    private static function normalizeWhitespace(string $text): string {
        $text = str_replace(["\r\n", "\r"], "\n", $text);
        $text = preg_replace('/[ \t\f\v]+/u', ' ', $text);
        $text = preg_replace('/ *\n+ */u', "\n", (string)$text);
        $text = preg_replace('/\n{3,}/u', "\n\n", (string)$text);

        return trim((string)$text);
    }
}
