import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from difflib import SequenceMatcher

# --- KELİME LİSTESİ ---
ARAPCA_KELIMELER = ["مَرْحَبًا", "شُكْرًا", "كِتَاب", "سَيَّارَة", "مَدْرَسَة"]
PORT = 8080 # Açılacak Port Numarası

# --- HTML, CSS VE JAVASCRIPT ---
HTML_SAYFASI = """
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <!-- MOBİL UYUM İÇİN EN ÖNEMLİ ETİKET (VIEWPORT) -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Arapça Telaffuz Testi</title>
    <style>
        /* MOBİL UYUMLU CSS AYARLARI */
        * { box-sizing: border-box; }
        body { 
            font-family: Arial, sans-serif; 
            text-align: center; 
            background-color: #f0f0f0; 
            margin: 0; 
            padding: 20px; 
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }
        .container { 
            background: white; 
            width: 100%; 
            max-width: 500px; /* PC'de en fazla 500px, telefonda ekranın %100'ü */
            padding: 30px 20px; 
            border-radius: 15px; 
            box-shadow: 0 10px 20px rgba(0,0,0,0.1); 
        }
        h2 { font-size: 20px; color: #34495e; }
        #kelime { 
            font-size: 3rem; /* Ekrana göre ölçeklenen font büyüklüğü */
            font-weight: bold; 
            color: #2c3e50; 
            margin: 30px 0; 
            direction: rtl; 
            word-wrap: break-word; /* Uzun kelimelerin taşmasını engeller */
        }
        button { 
            background: #3498db; 
            color: white; 
            border: none; 
            padding: 15px 20px; 
            font-size: 18px; 
            border-radius: 10px; 
            cursor: pointer; 
            width: 100%; /* Telefondaki parmakla basımı kolaylaştırmak için geniş buton */
            max-width: 300px;
            box-shadow: 0 4px 6px rgba(52, 152, 219, 0.3);
            transition: background 0.3s;
        }
        button:active { background: #2980b9; }
        button:disabled { background: #95a5a6; cursor: not-allowed; box-shadow: none; }
        #durum { margin-top: 25px; font-size: 18px; font-weight: bold; color: #7f8c8d; min-height: 50px; }
        .hata { color: #c0392b !important; }
        .basari { color: #27ae60 !important; }
    </style>
</head>
<body>
<div class="container">
    <h2>Aşağıdaki kelimeyi okuyun:</h2>
    <div id="kelime"></div>
    <button id="dinleBtn" onclick="dinlemeyeBasla()">🎤 Konuşmak İçin Tıkla</button>
    <div id="durum">Hazır.</div>
</div>

<script>
    const kelimeler = """ + json.dumps(ARAPCA_KELIMELER) + """;
    let index = 0;

    const kelimeDiv = document.getElementById("kelime");
    const durumDiv = document.getElementById("durum");
    const dinleBtn = document.getElementById("dinleBtn");

    kelimeDiv.innerText = kelimeler[index];

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition();
    recognition.lang = 'ar-SA';
    recognition.interimResults = false;

    function dinlemeyeBasla() {
        durumDiv.innerText = "Dinleniyor... Lütfen konuşun.";
        durumDiv.className = "";
        dinleBtn.disabled = true;
        recognition.start();
    }

    recognition.onresult = function(event) {
        const soylenenMetin = event.results[0][0].transcript;
        durumDiv.innerText = "Söylediğiniz işleniyor...";
        
        fetch('/kontrol', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 'hedef_kelime': kelimeler[index], 'soylenen': soylenenMetin })
        })
        .then(response => response.json())
        .then(data => {
            durumDiv.innerHTML = data.mesaj;
            if(data.durum === 'basarili') {
                durumDiv.className = "basari";
                index++;
                if(index < kelimeler.length) {
                    setTimeout(() => {
                        kelimeDiv.innerText = kelimeler[index];
                        durumDiv.innerText = "Yeni kelime için butona tıklayın.";
                        durumDiv.className = "";
                        dinleBtn.disabled = false;
                    }, 2500);
                } else {
                    kelimeDiv.innerText = "🎉";
                    durumDiv.innerText = "Tebrikler, tüm kelimeleri bitirdiniz!";
                    dinleBtn.style.display = 'none';
                }
            } else {
                durumDiv.className = "hata";
                dinleBtn.disabled = false;
            }
        });
    };

    recognition.onerror = function(event) {
        durumDiv.innerText = "Ses duyulamadı, tekrar deneyin.";
        durumDiv.className = "hata";
        dinleBtn.disabled = false;
    };
</script>
</body>
</html>
"""

# --- SUNUCU VE İSTEK YÖNETİCİSİ ---
class TelaffuzSunucusu(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(HTML_SAYFASI.encode('utf-8'))
        else:
            self.send_error(404)

    def do_POST(self):
        if self.path == '/kontrol':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            veri = json.loads(post_data.decode('utf-8'))

            hedef_kelime = veri.get('hedef_kelime', '')
            soylenen = veri.get('soylenen', '')

            # Kapalı Te (ة) -> He (ه) Dönüşümü (Ekranda gözükmez, kontrolde işe yarar)
            hedef_normalize = hedef_kelime.replace('ة', 'ه')
            soylenen_normalize = soylenen.replace('ة', 'ه')

            # Benzerlik Kontrolü (%70)
            benzerlik = SequenceMatcher(None, hedef_normalize, soylenen_normalize).ratio()

            if benzerlik > 0.70:
                yanit = {'durum': 'basarili', 'mesaj': f'Harika! Doğru telaffuz ettiniz. <br><small>(Duyulan: {soylenen})</small>'}
            else:
                yanit = {'durum': 'hata', 'mesaj': f'Yok, olmadı, tekrar deneyin. <br><small>(Duyulan: {soylenen})</small>'}

            self.send_response(200)
            self.send_header('Content-type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(json.dumps(yanit).encode('utf-8'))

# Sunucuyu Başlat
if __name__ == '__main__':
    server_address = ('0.0.0.0', PORT)
    httpd = HTTPServer(server_address, TelaffuzSunucusu)
    print(f"Sunucu başlatıldı! Tarayıcıdan http://localhost:{PORT} adresine gidebilirsiniz.")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nSunucu kapatılıyor...")
        httpd.server_close()