<?php
namespace EasyChat\Library\Email;

 
final class EmailReplyCleaner {
    public function clean(string $text): array {
        $text = str_replace(["\r\n", "\r"], "\n", trim($text));
        $lines = explode("\n", $text);
        $new = []; $quoted = []; $signature = []; $mode = 'new';
        foreach ($lines as $line) {
            if ($mode === 'new' && preg_match('/^\s*(?:--\s*$|С уважением[,!]?\s*$|Best regards[,]?\s*$|Отправлено с (?:iPhone|Android)|Sent from my)/iu', $line)) $mode = 'signature';
            if ($mode !== 'signature' && (preg_match('/^\s*>/', $line) || preg_match('/^\s*(?:On .+ wrote:|В .+ написал(?:а)?:|-----Original Message-----|От:|From:|Sent:)/iu', $line))) $mode = 'quoted';
            if ($mode === 'new') $new[] = $line; elseif ($mode === 'quoted') $quoted[] = $line; else $signature[] = $line;
        }
        $clean = trim(implode("\n", $new));
        $confidence = ($quoted || $signature) && $clean !== '' ? 0.92 : 0.70;
        return ['text'=>$clean !== '' ? $clean : $text, 'quoted'=>trim(implode("\n", $quoted)), 'signature'=>trim(implode("\n", $signature)), 'confidence'=>$confidence, 'cleaner_version'=>1];
    }
}
