<?php

namespace App\Services\Whmcs;

/**
 * Cheap language detector for the Bangladesh customer base. We only care
 * about three buckets:
 *   - bn   : Bangla script (U+0980..U+09FF) dominates
 *   - bn_latin : "Banglish" — Latin script transliteration of Bangla
 *                (heuristic: high frequency of common Banglish tokens)
 *   - en   : English
 *
 * Output drives the reply prompt: "reply in Bangla script" / "reply in
 * Banglish so it reads like the customer's own typing" / "reply in English".
 *
 * Deliberately not using a real lib — we don't need ML for this. Char-class
 * counting + a small Banglish stoplist gets >95% accuracy on the actual
 * ticket corpus.
 */
class LanguageDetector
{
    /**
     * Common Banglish tokens — Latin transliterations of high-frequency
     * Bangla words. Hit rate of 2+ in a message → flag as Banglish.
     */
    private const BANGLISH_MARKERS = [
        'ami', 'ami', 'amar', 'amake', 'tumi', 'apni', 'apnar',
        'kemne', 'kivabe', 'koto', 'koi', 'kothay', 'keno',
        'hocche', 'hobe', 'korbe', 'korte', 'korechi', 'kore',
        'thaki', 'thakbe', 'theke', 'jonno', 'lagbe', 'darkar',
        'ace', 'ase', 'naki', 'na', 'jay', 'eta', 'oi', 'ei',
        'kicu', 'kichu', 'sudhu', 'sob', 'kew', 'r ', 'are', 'ar ',
        'bhai', 'bro', 'help korben', 'kosto', 'cesta', 'cesta korlam',
    ];

    public static function detect(string $text): string
    {
        if (! $text) return 'en';

        // Bangla script char count.
        preg_match_all('/[\x{0980}-\x{09FF}]/u', $text, $banglaChars);
        $banglaCount = count($banglaChars[0] ?? []);
        // Latin alphabet char count (rough — includes ASCII letters only).
        preg_match_all('/[A-Za-z]/', $text, $latinChars);
        $latinCount = count($latinChars[0] ?? []);

        $totalScript = $banglaCount + $latinCount;
        if ($totalScript === 0) return 'en';

        // Bangla script dominant → bn
        if ($banglaCount / $totalScript > 0.30) return 'bn';

        // No Bangla script — check for Banglish.
        $lower = strtolower($text);
        $hits = 0;
        foreach (self::BANGLISH_MARKERS as $tok) {
            // Word-boundary-ish match (preceded/followed by space or punct).
            if (preg_match('/(^|[\s.,!?])' . preg_quote($tok, '/') . '(?=$|[\s.,!?])/u', $lower)) {
                $hits++;
                if ($hits >= 2) return 'bn_latin';
            }
        }

        return 'en';
    }

    public static function describe(string $code): string
    {
        return match ($code) {
            'bn'       => 'Bangla (Bengali script)',
            'bn_latin' => 'Banglish (Bangla typed in Latin script — common informal style)',
            default    => 'English',
        };
    }

    public static function instructionFor(string $code): string
    {
        return match ($code) {
            'bn'       => 'Reply in Bangla (Bengali script). Use natural conversational Bangla, not stiff formal Bangla. Mix in English technical terms (cPanel, password, server, domain) where they read more naturally — that\'s how Bangladeshi customers actually talk.',
            // Banglish input → Bangla-script reply. The customer typed in
            // Latin transliteration but a professional support reply MUST
            // be in proper Bangla script for HostSeba\'s brand voice.
            // Mirror their warmth and informality, not their script.
            'bn_latin' => 'Reply in Bangla (Bengali script — NOT Banglish). The customer wrote in Latin transliteration but a professional support reply MUST be in proper Bangla script. Use natural conversational Bangla (not stiff formal শুভেচ্ছান্তে register), mix in English technical terms (cPanel, MongoDB, port, IP, server, password) where they read naturally. Do NOT mirror their Latin transliteration back — write in proper বাংলা.',
            default    => 'Reply in English. Clear, professional, no over-formality.',
        };
    }
}
