from flask import Flask, render_template_string, request, jsonify, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from openai import OpenAI
import os
import uuid
import random
import json

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-gizli-anahtar'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:Mmty2676*@localhost/arapca_app'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# --- OPENAI API AYARI ---
# UYARI: Güvenliğin için yeni bir API Key oluşturup burayı değiştirmelisin!
client = OpenAI(api_key="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")

UPLOAD_FOLDER = 'static/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    role = db.Column(db.String(20), default='user')
    score = db.Column(db.Integer, default=0)

class Unit(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    lessons = db.relationship('Lesson', backref='unit', cascade="all, delete-orphan", lazy=True)

class Lesson(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'), nullable=False)
    title = db.Column(db.String(100), nullable=False)
    words = db.relationship('Word', backref='lesson', cascade="all, delete-orphan", lazy=True)

class Word(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    lesson_id = db.Column(db.Integer, db.ForeignKey('lesson.id'), nullable=False)
    ar = db.Column(db.String(100), nullable=False)
    tr = db.Column(db.String(100), nullable=False)
    q_type = db.Column(db.String(20), nullable=False)
    audio_file = db.Column(db.String(255), nullable=True)

class CompletedLesson(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    lesson_id = db.Column(db.Integer, db.ForeignKey('lesson.id'), nullable=False)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

GLOBAL_HTML_START = """
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;700;900&family=Tajawal:wght@700&display=swap');
        :root { --primary: #1CB0F6; --primary-dark: #1899D6; --success: #58CC02; --success-dark: #58A700; --danger: #FF4B4B; --danger-dark: #EA1538; --bg: #F7F7F7; --text: #4B4B4B; --warning: #FFC800; --warning-dark: #E5B400; }
        * { box-sizing: border-box; font-family: 'Nunito', sans-serif; }
        body { background-color: var(--bg); color: var(--text); margin: 0; padding: 15px; display: flex; flex-direction: column; align-items: center; min-height: 100vh; }
        .card { background: white; border-radius: 20px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); padding: 25px; width: 100%; max-width: 600px; margin-bottom: 20px; text-align: center; border: 2px solid #E5E5E5; }
        h1, h2, h3 { color: #3C3C3C; }
        input[type="text"], input[type="password"], select { width: 100%; padding: 15px; margin: 8px 0; border: 2px solid #E5E5E5; border-radius: 12px; font-size: 16px; outline: none; background: #fff; }
        .btn { display: inline-block; padding: 15px; border-radius: 12px; font-size: 18px; font-weight: bold; color: white; cursor: pointer; border: none; text-decoration: none; margin-top: 5px; width: 100%; text-align:center; }
        .btn-blue { background-color: var(--primary); box-shadow: 0 4px 0 var(--primary-dark); }
        .btn-green { background-color: var(--success); box-shadow: 0 4px 0 var(--success-dark); }
        .btn-red { background-color: var(--danger); box-shadow: 0 4px 0 var(--danger-dark); }
        .btn-yellow { background-color: var(--warning); box-shadow: 0 4px 0 var(--warning-dark); color: #B38C00; }
        .btn:disabled { background-color: #E5E5E5; box-shadow: 0 4px 0 #CECECE; cursor: not-allowed; color: #AFAFAF; }
        .arabic-text { font-family: 'Tajawal', sans-serif; font-size: 3.5rem; color: #2C3E50; direction: rtl; margin: 20px 0; }
        .badge { background: #FFC800; color: #B38C00; padding: 8px 15px; border-radius: 20px; font-weight: 900; display: inline-block; margin-bottom: 15px; }
        .admin-box { background: #f9f9f9; border: 2px solid #eee; padding: 15px; border-radius: 15px; margin-bottom: 15px; text-align: left; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size:14px; }
        th, td { padding: 8px; border-bottom: 1px solid #ddd; text-align: left; }
        
        .avatar-wrapper { position: relative; width: 140px; height: 140px; margin: 0 auto 10px; perspective: 500px; }
        .avatar { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); width: 100px; height: 130px; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); transform-origin: bottom center; }
        .head { background: #ffccb4; width: 80px; height: 90px; border-radius: 40px 40px 30px 30px; position: absolute; top: 10px; left: 10px; z-index: 2; transition: all 0.3s; box-shadow: inset -4px -6px 10px rgba(0,0,0,0.1); }
        .hair { background: #3b2818; width: 84px; height: 35px; border-radius: 40px 40px 10px 10px; position: absolute; top: -5px; left: -2px; }
        .ear { background: #ffccb4; width: 20px; height: 26px; border-radius: 10px; position: absolute; top: 38px; z-index: 1; transition: all 0.3s; box-shadow: inset -2px -2px 5px rgba(0,0,0,0.1); }
        .ear.left { left: 0px; } .ear.right { right: 0px; }
        .eye { background: #2c3e50; width: 10px; height: 12px; border-radius: 50%; position: absolute; top: 42px; transition: all 0.2s; }
        .eye.left { left: 22px; } .eye.right { right: 22px; }
        .mouth { background: #8b3e3e; width: 22px; height: 6px; border-radius: 10px; position: absolute; top: 68px; left: 29px; transition: all 0.1s; }
        .torso { background: var(--primary); width: 100px; height: 45px; border-radius: 40px 40px 10px 10px; position: absolute; bottom: 0; left: 0; z-index: 0; box-shadow: inset 0 5px 10px rgba(0,0,0,0.1); }
        
        .avatar.talking .mouth { animation: talkAnim 0.25s infinite alternate; height: 18px; border-radius: 10px 10px 20px 20px; top: 63px; background: #5c1b1b; }
        @keyframes talkAnim { 0% { height: 6px; top: 68px; } 100% { height: 18px; top: 63px; } }
        .avatar.listening { transform: translateX(-50%) scale(1.15) rotate(4deg); }
        .avatar.listening .head { transform: translateY(5px); }
        .avatar.listening .ear { transform: scale(1.4) rotate(15deg); background: #ffb595; }
        .avatar.listening .ear.left { transform: scale(1.4) rotate(-15deg); left: -5px; }
        .avatar.listening .ear.right { transform: scale(1.4) rotate(15deg); right: -5px; }
        .avatar.listening .eye { height: 16px; top: 40px; } 
        .flash { background: var(--danger); color: white; padding: 10px; border-radius: 10px; margin-bottom: 15px; font-weight: bold; }
    </style>
</head>
<body>
"""
GLOBAL_HTML_END = "</body></html>"

HTML_DASHBOARD = GLOBAL_HTML_START + """
<title>Yol Haritası</title>
<div class="card">
    <h2>Merhaba, {{ user.username }}! 🌟</h2>
    <div class="badge" style="font-size:18px;">Puanın: {{ user.score }} XP</div>
    {% if user.role == 'admin' %}<a href="/admin" class="btn btn-red" style="margin-bottom:20px;">👑 ADMİN PANELİNE GİT</a>{% endif %}
    <a href="/logout" style="color:#AFAFAF; font-weight:bold; text-decoration:none; display:block; margin-bottom:20px; padding:10px;">Çıkış Yap</a>

    {% for u in units %}
        <div style="background:#F0F9FF; border:2px solid var(--primary); padding:15px; border-radius:20px; margin-bottom:20px; text-align:left;">
            <h3 style="margin:0 0 10px 0; color:var(--primary-dark);">📚 {{ u.title }}</h3>
            {% for lesson in u.lessons %}
                <div style="background:white; padding:15px; border-radius:12px; margin-bottom:10px; display:flex; flex-direction:column; gap:10px; border:1px solid #eee;">
                    <span style="font-weight:bold; font-size:16px;">
                        {% if lesson.id in completed_ids %}✅{% else %}⚪{% endif %} 
                        {{ lesson.title }} ({{ lesson.words|length }} Kelime)
                    </span>
                    
                    {% if lesson.id in completed_ids %}
                        <a href="/lesson/{{ lesson.id }}" class="btn btn-yellow" style="padding:10px;">Tekrar Et (+ Az XP)</a>
                    {% else %}
                        <a href="/lesson/{{ lesson.id }}" class="btn btn-green" style="padding:10px;">Derse Başla</a>
                    {% endif %}
                </div>
            {% endfor %}
        </div>
    {% endfor %}
</div>
""" + GLOBAL_HTML_END

# YENİ JAVASCRIPT: OPENAI SES KAYIT SİSTEMİ
HTML_LESSON = GLOBAL_HTML_START + """
<title>Ders Ekranı</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<div class="card">
    <div class="avatar-wrapper">
        <div id="avatar" class="avatar">
            <div class="torso"></div><div class="ear left"></div><div class="ear right"></div>
            <div class="head"><div class="hair"></div><div class="eye left"></div><div class="eye right"></div><div class="mouth"></div></div>
        </div>
    </div>
    
    <div id="soru-tipi" class="badge">Yükleniyor...</div>
    <div id="kelime" class="arabic-text"></div>
    <h3 id="anlam" style="color:#AFAFAF;"></h3>
    
    <button id="aksiyonBtn" class="btn btn-blue" onclick="aksiyonYap()">BAŞLA</button>
    <p id="durum" style="font-weight:bold; margin-top:15px; font-size:16px;"></p>
    <a href="/dashboard" style="display:block; margin-top:20px; color:#AFAFAF; font-weight:bold; text-decoration:none; padding:10px;">Dersi Terk Et</a>
</div>

<script>
    const kelimeler = {{ words|tojson }};
    const lesson_id = {{ lesson_id }};
    let index = 0;

    let mediaRecorder;
    let audioChunks = [];
    let isRecording = false;

    const kelimeDiv = document.getElementById("kelime");
    const anlamDiv = document.getElementById("anlam");
    const durumDiv = document.getElementById("durum");
    const aksiyonBtn = document.getElementById("aksiyonBtn");
    const soruTipiDiv = document.getElementById("soru-tipi");
    const avatar = document.getElementById("avatar"); 

    function setIdle() { avatar.className = "avatar"; }
    function setTalking() { avatar.className = "avatar talking"; }
    function setListening() { avatar.className = "avatar listening"; }

    function ekraniGuncelle() {
        setIdle(); 
        if(kelimeler.length === 0) return window.location.href='/dashboard';
        if(index >= kelimeler.length) {
            fetch('/finish_lesson/' + lesson_id, {method: 'POST'}).then(() => {
                Swal.fire('Tebrikler!', 'Dersi tamamladın!', 'success').then(() => window.location.href = '/dashboard');
            });
            return;
        }
        
        let current = kelimeler[index];
        anlamDiv.innerText = current.tr;
        
        if(current.q_type === 'speaking') {
            soruTipiDiv.innerText = "Ekranda yazanı oku.";
            kelimeDiv.innerText = current.ar;
            aksiyonBtn.innerText = "🎤 KAYDA BAŞLA";
            aksiyonBtn.className = "btn btn-blue";
        } else if (current.q_type === 'listening') {
            soruTipiDiv.innerText = "Duyduğunu Arapça söyle.";
            kelimeDiv.innerText = "🔊 ❓❓❓"; 
            aksiyonBtn.innerText = "▶️ DİNLE VE SÖYLE";
            aksiyonBtn.className = "btn btn-green";
        } else if (current.q_type === 'repeat') {
            soruTipiDiv.innerText = "Benden sonra tekrar et.";
            kelimeDiv.innerText = current.ar;
            aksiyonBtn.innerText = "🔁 DİNLE VE TEKRAR ET";
            aksiyonBtn.className = "btn btn-blue";
        }
    }

    function gercekSesOku(audioUrl, callback) {
        if(!audioUrl) { durumDiv.innerText = "Ses dosyası yok!"; setTimeout(callback, 2000); return; }
        setTalking(); 
        let ses = new Audio("/static/uploads/" + audioUrl);
        ses.play();
        ses.onended = function() { setIdle(); callback(); };
    }

    function aksiyonYap() {
        let current = kelimeler[index];

        // Eğer şu an kayıt yapıyorsa, kaydı durdur.
        if(isRecording) {
            mediaRecorder.stop();
            return;
        }

        if(current.q_type === 'speaking') { dinlemeyeBasla(); } 
        else {
            durumDiv.innerText = "🔊 Sistem konuşuyor...";
            aksiyonBtn.disabled = true;
            gercekSesOku(current.audio_file, () => { dinlemeyeBasla(); });
        }
    }

    function dinlemeyeBasla() {
        navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
            mediaRecorder = new MediaRecorder(stream);
            mediaRecorder.start();
            isRecording = true;
            audioChunks = [];

            setListening(); 
            durumDiv.innerText = "Sıra sende, konuşuluyor... Bitince butona bas.";
            durumDiv.style.color = "var(--primary)";
            
            aksiyonBtn.disabled = false;
            aksiyonBtn.innerText = "⏹️ KAYDI BİTİR VE GÖNDER";
            aksiyonBtn.className = "btn btn-red";

            mediaRecorder.addEventListener("dataavailable", event => { audioChunks.push(event.data); });
            mediaRecorder.addEventListener("stop", () => {
                isRecording = false;
                setIdle();
                aksiyonBtn.disabled = true;
                durumDiv.innerText = "Yapay Zeka Sesini Analiz Ediyor... Lütfen bekle 🤖";
                
                const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                const formData = new FormData();
                formData.append("audio", audioBlob);
                formData.append("hedef_kelime", kelimeler[index].ar);
                formData.append("lesson_id", lesson_id);

                fetch('/kontrol', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    if(data.durum === 'basarili') {
                        Swal.fire({ title: 'Harika!', html: data.mesaj, icon: 'success', timer: 2000, showConfirmButton: false });
                        index++;
                        setTimeout(() => { aksiyonBtn.disabled = false; durumDiv.innerText=""; ekraniGuncelle(); }, 2000);
                    } else {
                        Swal.fire({ title: 'Telaffuz Hatası!', html: data.mesaj, icon: 'error' });
                        aksiyonBtn.disabled = false;
                        durumDiv.innerText = "Tekrar deneyin.";
                        ekraniGuncelle(); // Butonu eski haline çevirmek için
                    }
                }).catch(err => {
                    Swal.fire('Hata', 'Sunucuya bağlanılamadı.', 'error');
                    aksiyonBtn.disabled = false;
                    ekraniGuncelle();
                });
            });
        }).catch(err => {
            Swal.fire('Hata', 'Mikrofon izni verilmedi veya desteklenmiyor.', 'error');
        });
    }

    ekraniGuncelle();
</script>
""" + GLOBAL_HTML_END

HTML_ADMIN = GLOBAL_HTML_START + """
<title>Admin Paneli</title>
<div class="card" style="max-width:800px; padding:15px;">
    <h2 style="color:var(--danger);">👑 ADMİN PANELİ</h2>
    <a href="/dashboard" class="btn btn-blue" style="margin-bottom:20px;">Ana Sayfaya Dön</a>
    <div class="admin-box">
        <h3>Yeni Ünite Ekle</h3>
        <form action="/admin/add_unit" method="POST" style="display:flex; gap:10px;">
            <input type="text" name="title" placeholder="Ünite Adı" required style="margin:0;">
            <button type="submit" class="btn btn-blue" style="margin:0; width:150px;">Ekle</button>
        </form>
    </div>
    {% for u in units %}
        <div class="admin-box" style="border-color:var(--primary);">
            <div style="display:flex; justify-content:space-between; align-items:center; background:#e0f2fe; padding:10px; border-radius:10px;">
                <h3 style="color:var(--primary); margin:0;">📂 {{ u.title }}</h3>
                <a href="/admin/delete_unit/{{ u.id }}" onclick="return confirm('Emin misin?')" class="btn btn-red" style="padding:5px 10px; width:auto; margin:0;">🗑️</a>
            </div>
            <form action="/admin/add_lesson" method="POST" style="display:flex; gap:10px; margin-top:10px;">
                <input type="hidden" name="unit_id" value="{{ u.id }}">
                <input type="text" name="title" placeholder="Bu üniteye Yeni Ders Ekle" required style="margin:0;">
                <button type="submit" class="btn btn-green" style="margin:0; width:150px;">Ders Ekle</button>
            </form>
            {% for lesson in u.lessons %}
                <div style="background:white; border:1px solid #ccc; padding:10px; margin-top:15px; border-radius:10px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:2px solid #eee; padding-bottom:10px; margin-bottom:10px;">
                        <h4 style="margin:0; color:var(--success-dark);">📄 {{ lesson.title }}</h4>
                        <a href="/admin/delete_lesson/{{ lesson.id }}" onclick="return confirm('Emin misin?')" class="btn btn-red" style="padding:5px 10px; width:auto; margin:0;">🗑️</a>
                    </div>
                    <form action="/admin/add_word" method="POST" enctype="multipart/form-data" style="display:flex; flex-direction:column; gap:8px; margin-bottom:10px; background:#f0f9ff; padding:10px; border-radius:10px;">
                        <input type="hidden" name="lesson_id" value="{{ lesson.id }}">
                        <input type="text" name="ar" placeholder="Arapça Kelime (Harekeli Giriniz)" required style="direction:rtl; font-family:'Tajawal'; font-size:20px;">
                        <input type="text" name="tr" placeholder="Türkçe Anlamı" required>
                        <select name="q_type" onchange="this.nextElementSibling.style.display = (this.value == 'speaking') ? 'none' : 'block';">
                            <option value="speaking">Konuşma</option>
                            <option value="listening">Dinleme</option>
                            <option value="repeat">Tekrar</option>
                        </select>
                        <div style="display:none;">
                            <label style="font-weight:bold; color:var(--danger); font-size:14px;">🔊 Ses Dosyası Yükle:</label>
                            <input type="file" name="audio" accept="audio/*">
                        </div>
                        <button type="submit" class="btn btn-blue">Kelimeyi Ekle</button>
                    </form>
                    {% if lesson.words %}
                    <div style="overflow-x:auto;">
                        <table>
                            <tr><th>Arapça</th><th>Türkçe</th><th>Tür</th><th>İşlem</th></tr>
                            {% for w in lesson.words %}
                            <tr>
                                <td style="direction:rtl; font-weight:bold; font-size:18px;">{{ w.ar }}</td>
                                <td>{{ w.tr }}</td><td>{{ w.q_type }}</td>
                                <td><a href="/admin/delete_word/{{ w.id }}" class="btn btn-red" style="padding:5px; width:auto; margin:0;">🗑️</a></td>
                            </tr>
                            {% endfor %}
                        </table>
                    </div>
                    {% endif %}
                </div>
            {% endfor %}
        </div>
    {% endfor %}
</div>
""" + GLOBAL_HTML_END

@app.route('/')
def index(): return redirect(url_for('dashboard')) if current_user.is_authenticated else redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated: return redirect(url_for('dashboard'))
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form['username']).first()
        if user and check_password_hash(user.password, request.form['password']):
            login_user(user, remember=(True if request.form.get('remember') else False))
            return redirect(url_for('dashboard'))
    html = GLOBAL_HTML_START + "<title>Giriş</title><div class='card'><h2>Giriş Yap</h2><form method='POST'><input type='text' name='username' placeholder='Kullanıcı Adı' required><input type='password' name='password' placeholder='Şifre' required><div style='display:flex; align-items:center; margin: 15px 5px; justify-content:left;'><input type='checkbox' name='remember' id='remember' style='width:20px; height:20px; margin:0 10px 0 0;'><label for='remember' style='font-weight:bold;'>Beni Hatırla</label></div><button class='btn btn-blue'>GİRİŞ</button></form><a href='/register' style='display:block; margin-top:20px; color:var(--primary); font-weight:bold;'>Kayıt Ol</a></div>" + GLOBAL_HTML_END
    return render_template_string(html)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated: return redirect(url_for('dashboard'))
    if request.method == 'POST':
        if User.query.filter_by(username=request.form['username']).first(): pass
        else:
            db.session.add(User(username=request.form['username'], password=generate_password_hash(request.form['password'])))
            db.session.commit()
            return redirect(url_for('login'))
    html = GLOBAL_HTML_START + "<title>Kayıt</title><div class='card'><h2>Kayıt Ol</h2><form method='POST'><input type='text' name='username' placeholder='Kullanıcı Adı' required><input type='password' name='password' placeholder='Şifre' required><button class='btn btn-green'>KAYIT OL</button></form><a href='/login' style='display:block; margin-top:20px; color:var(--primary); font-weight:bold;'>Zaten hesabım var (Giriş)</a></div>" + GLOBAL_HTML_END
    return render_template_string(html)

@app.route('/logout')
@login_required
def logout(): logout_user(); return redirect(url_for('login'))

@app.route('/dashboard')
@login_required
def dashboard():
    units = Unit.query.all()
    completed_ids = [c.lesson_id for c in CompletedLesson.query.filter_by(user_id=current_user.id).all()]
    return render_template_string(HTML_DASHBOARD, user=current_user, units=units, completed_ids=completed_ids)

@app.route('/lesson/<int:lesson_id>')
@login_required
def lesson(lesson_id):
    lesson_data = Lesson.query.get_or_404(lesson_id)
    words = [{"ar": w.ar, "tr": w.tr, "q_type": w.q_type, "audio_file": w.audio_file} for w in lesson_data.words]
    random.shuffle(words)
    return render_template_string(HTML_LESSON, words=words, lesson_id=lesson_id)

# YENİ OPENAI YAPAY ZEKA KONTROL SİSTEMİ
@app.route('/kontrol', methods=['POST'])
@login_required
def kontrol():
    hedef = request.form.get('hedef_kelime', '')
    lesson_id = request.form.get('lesson_id')
    audio_file = request.files.get('audio')

    if not audio_file:
        return jsonify({'durum': 'hata', 'mesaj': 'Ses alınamadı.'})

    temp_path = f"temp_{uuid.uuid4()}.webm"
    audio_file.save(temp_path)

    try:
        # 1. Aşama: Sesi Yazıya Çevir (Whisper)
        with open(temp_path, "rb") as audio:
            transcript = client.audio.transcriptions.create(
                model="whisper-1",
                file=audio,
                language="ar"
            )
        soylenen = transcript.text

        # 2. Aşama: Uzman Değerlendirmesi (GPT-4o)
        prompt = f"""
        Sen bir Arapça dil, tecvid ve telaffuz uzmanısın. Kullanıcının söylediği kelime ile hedef kelimeyi karşılaştır.
        Hedef Kelime: {hedef}
        Kullanıcının Söylediği: {soylenen}

        KURALLAR:
        1. Özellikle HAREKE (üstün, esre, ötre hataları) ve MED (uzatma harflerinin eksikliği veya fazlalığı) hatalarını ara.
        2. Ufak tefek noktalama işaretlerini görmezden gel.
        3. Eğer telaffuz doğruysa JSON "durum" değeri "basarili" olsun.
        4. Eğer hareke veya uzatma hatası varsa (veya tamamen başka bir şey söylediyse) "durum" değeri "hata" olsun.
        5. "mesaj" kısmına kullanıcıya HTML tagları kullanarak (örneğin <b> kalın yazarak) kibar, Türkçe ve eğitici bir geri bildirim ver. Neyin yanlış olduğunu açıkla.

        ÇIKTI FORMATI SADECE AŞAĞIDAKİ GİBİ JSON OLMALIDIR:
        {{"durum": "basarili" veya "hata", "mesaj": "Açıklamanız"}}
        """

        response = client.chat.completions.create(
            model="gpt-4o", # En zeki model
            response_format={ "type": "json_object" },
            messages=[
                {"role": "system", "content": "You are a strict Arabic pronunciation API that outputs only JSON."},
                {"role": "user", "content": prompt}
            ]
        )
        
        sonuc_json = json.loads(response.choices[0].message.content)

        # 3. Aşama: Eğer başarılıysa puan ver
        if sonuc_json.get('durum') == 'basarili':
            is_completed = CompletedLesson.query.filter_by(user_id=current_user.id, lesson_id=lesson_id).first()
            kazanilan_puan = 2 if is_completed else 10
            current_user.score += kazanilan_puan
            db.session.commit()
            sonuc_json['mesaj'] += f"<br><br><span style='color:green;'><b>+{kazanilan_puan} XP Kazandın!</b></span>"

    except Exception as e:
        sonuc_json = {'durum': 'hata', 'mesaj': f'Yapay zeka analizinde hata oluştu: {str(e)}'}
    finally:
        if os.path.exists(temp_path):
            os.remove(temp_path)

    return jsonify(sonuc_json)

@app.route('/finish_lesson/<int:lesson_id>', methods=['POST'])
@login_required
def finish_lesson(lesson_id):
    if not CompletedLesson.query.filter_by(user_id=current_user.id, lesson_id=lesson_id).first():
        db.session.add(CompletedLesson(user_id=current_user.id, lesson_id=lesson_id))
        db.session.commit()
    return "OK"

@app.route('/admin')
@login_required
def admin():
    if current_user.role != 'admin': return redirect(url_for('dashboard'))
    units = Unit.query.all()
    return render_template_string(HTML_ADMIN, units=units)

@app.route('/admin/add_unit', methods=['POST'])
@login_required
def add_unit():
    if current_user.role == 'admin': db.session.add(Unit(title=request.form['title'])); db.session.commit()
    return redirect(url_for('admin'))

@app.route('/admin/add_lesson', methods=['POST'])
@login_required
def add_lesson():
    if current_user.role == 'admin': db.session.add(Lesson(unit_id=request.form['unit_id'], title=request.form['title'])); db.session.commit()
    return redirect(url_for('admin'))

@app.route('/admin/add_word', methods=['POST'])
@login_required
def add_word():
    if current_user.role == 'admin':
        audio_filename = None
        if request.form['q_type'] in ['listening', 'repeat']:
            file = request.files.get('audio')
            if file and file.filename != '':
                ext = file.filename.rsplit('.', 1)[-1].lower()
                audio_filename = str(uuid.uuid4()) + '.' + ext
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], audio_filename))
        db.session.add(Word(lesson_id=request.form['lesson_id'], ar=request.form['ar'], tr=request.form['tr'], q_type=request.form['q_type'], audio_file=audio_filename))
        db.session.commit()
    return redirect(url_for('admin'))

@app.route('/admin/delete_unit/<int:id>')
@login_required
def delete_unit(id):
    if current_user.role == 'admin': Unit.query.filter_by(id=id).delete(); db.session.commit()
    return redirect(url_for('admin'))

@app.route('/admin/delete_lesson/<int:id>')
@login_required
def delete_lesson(id):
    if current_user.role == 'admin': Lesson.query.filter_by(id=id).delete(); db.session.commit()
    return redirect(url_for('admin'))

@app.route('/admin/delete_word/<int:id>')
@login_required
def delete_word(id):
    if current_user.role == 'admin': Word.query.filter_by(id=id).delete(); db.session.commit()
    return redirect(url_for('admin'))

with app.app_context():
    db.create_all()
    if not User.query.filter_by(username='Mervan').first(): db.session.add(User(username='Mervan', password=generate_password_hash('Mmty2676*'), role='admin'))
    if not User.query.filter_by(username='Merve').first(): db.session.add(User(username='Merve', password=generate_password_hash('2676274'), role='admin'))
    db.session.commit()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
