#!/usr/bin/env python3
"""
Sözlük Veritabanı Yönetim Paneli
- Kayıt listeleme (checkbox ile seçim)
- Toplu silme
- Tekli düzenleme
- Yeni kayıt ekleme
- Arama ve filtreleme
"""

import sqlite3
from flask import Flask, render_template_string, jsonify, request
import os

app = Flask(__name__)

DATABASE = '/mnt/pdfs/dictionary.db'

def get_db():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

HTML_TEMPLATE = '''
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sözlük Yönetimi</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            min-height: 100vh;
            color: #e0e0e0;
        }
        
        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: rgba(255, 207, 0, 0.1);
            border: 1px solid #ffcf00;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        h1 {
            color: #ffcf00;
            font-size: 1.8em;
        }
        
        .stats {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .stat-box {
            background: rgba(0,0,0,0.3);
            padding: 10px 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-box .number {
            font-size: 1.5em;
            font-weight: bold;
            color: #ffcf00;
        }
        
        .stat-box .label {
            font-size: 0.8em;
            color: #888;
        }
        
        .controls {
            background: rgba(0,0,0,0.2);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        
        input[type="text"], select {
            background: rgba(255,255,255,0.1);
            border: 1px solid #444;
            color: #fff;
            padding: 10px 15px;
            border-radius: 6px;
            font-size: 14px;
        }
        
        input[type="text"]:focus, select:focus {
            outline: none;
            border-color: #ffcf00;
        }
        
        #searchInput {
            width: 300px;
        }
        
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
        }
        
        .btn-primary {
            background: #ffcf00;
            color: #000;
        }
        
        .btn-primary:hover {
            background: #e6ba00;
        }
        
        .btn-danger {
            background: #dc3545;
            color: #fff;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .btn-success {
            background: #28a745;
            color: #fff;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: #fff;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .selection-info {
            background: rgba(255, 207, 0, 0.2);
            padding: 8px 15px;
            border-radius: 6px;
            color: #ffcf00;
            font-weight: 500;
        }
        
        .table-container {
            background: rgba(0,0,0,0.2);
            border-radius: 12px;
            overflow: hidden;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th {
            background: rgba(255, 207, 0, 0.1);
            color: #ffcf00;
            padding: 15px 10px;
            text-align: left;
            font-weight: 600;
            position: sticky;
            top: 0;
        }
        
        td {
            padding: 12px 10px;
            border-bottom: 1px solid rgba(255,255,255,0.05);
        }
        
        tr:hover {
            background: rgba(255, 207, 0, 0.05);
        }
        
        tr.selected {
            background: rgba(255, 207, 0, 0.15) !important;
        }
        
        .checkbox-cell {
            width: 40px;
            text-align: center;
        }
        
        input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: #ffcf00;
        }
        
        .category-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            background: rgba(255,255,255,0.1);
        }
        
        .cat-parts-catalog { background: #28a745; color: #fff; }
        .cat-katalog-detailed { background: #17a2b8; color: #fff; }
        .cat-table { background: #6c757d; color: #fff; }
        .cat-general { background: #ffc107; color: #000; }
        .cat-deep-scan { background: #dc3545; color: #fff; }
        .cat-maden { background: #6f42c1; color: #fff; }
        .cat-equipment { background: #fd7e14; color: #fff; }
        
        .actions-cell {
            width: 100px;
        }
        
        .btn-edit {
            background: #17a2b8;
            color: #fff;
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .btn-edit:hover {
            background: #138496;
        }
        
        /* Modal */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-overlay.active {
            display: flex;
        }
        
        .modal {
            background: #1a1a2e;
            border: 1px solid #ffcf00;
            border-radius: 12px;
            padding: 30px;
            width: 500px;
            max-width: 90%;
        }
        
        .modal h2 {
            color: #ffcf00;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #888;
            font-size: 13px;
        }
        
        .form-group input, .form-group select {
            width: 100%;
        }
        
        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            padding: 20px;
        }
        
        .page-info {
            color: #888;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #888;
        }
        
        .loading::after {
            content: '';
            animation: dots 1.5s infinite;
        }
        
        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60%, 100% { content: '...'; }
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 8px;
            color: #fff;
            font-weight: 500;
            z-index: 2000;
            animation: slideIn 0.3s ease;
        }
        
        .toast.success { background: #28a745; }
        .toast.error { background: #dc3545; }
        
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>📚 Sözlük Yönetimi</h1>
            <div class="stats">
                <div class="stat-box">
                    <div class="number" id="totalCount">-</div>
                    <div class="label">Toplam</div>
                </div>
                <div class="stat-box">
                    <div class="number" id="filteredCount">-</div>
                    <div class="label">Gösterilen</div>
                </div>
                <div class="stat-box">
                    <div class="number" id="categoryCount">-</div>
                    <div class="label">Kategori</div>
                </div>
            </div>
        </header>
        
        <div class="controls">
            <input type="text" id="searchInput" placeholder="🔍 Ara (İngilizce/Türkçe)..." onkeyup="debounceSearch()">
            
            <select id="categoryFilter" onchange="loadData()">
                <option value="">Tüm Kategoriler</option>
            </select>
            
            <select id="limitSelect" onchange="loadData()">
                <option value="50">50</option>
                <option value="100" selected>100</option>
                <option value="200">200</option>
                <option value="500">500</option>
                <option value="1000">1000</option>
            </select>
            
            <button class="btn-success" onclick="openAddModal()">➕ Yeni Ekle</button>
            
            <div style="flex-grow: 1;"></div>
            
            <span class="selection-info" id="selectionInfo" style="display: none;">
                <span id="selectedCount">0</span> seçili
            </span>
            
            <button class="btn-danger" id="deleteSelectedBtn" onclick="deleteSelected()" style="display: none;">
                🗑️ Seçilenleri Sil
            </button>
        </div>
        
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th class="checkbox-cell">
                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                        </th>
                        <th>İngilizce</th>
                        <th>Türkçe</th>
                        <th>Kategori</th>
                        <th>Güven</th>
                        <th class="actions-cell">İşlem</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <tr><td colspan="6" class="loading">Yükleniyor</td></tr>
                </tbody>
            </table>
        </div>
        
        <div class="pagination">
            <button class="btn-secondary" id="prevBtn" onclick="prevPage()">◀ Önceki</button>
            <span class="page-info">Sayfa <span id="currentPage">1</span> / <span id="totalPages">1</span></span>
            <button class="btn-secondary" id="nextBtn" onclick="nextPage()">Sonraki ▶</button>
        </div>
    </div>
    
    <!-- Edit/Add Modal -->
    <div class="modal-overlay" id="modal">
        <div class="modal">
            <h2 id="modalTitle">Kayıt Düzenle</h2>
            <input type="hidden" id="editId">
            
            <div class="form-group">
                <label>İngilizce (canonical_en)</label>
                <input type="text" id="editEn" placeholder="English term...">
            </div>
            
            <div class="form-group">
                <label>Türkçe (canonical_tr)</label>
                <input type="text" id="editTr" placeholder="Türkçe karşılık...">
            </div>
            
            <div class="form-group">
                <label>Kategori</label>
                <select id="editCategory"></select>
            </div>
            
            <div class="form-group">
                <label>Güven Skoru (0-1)</label>
                <input type="text" id="editConfidence" placeholder="0.95">
            </div>
            
            <div class="modal-buttons">
                <button class="btn-secondary" onclick="closeModal()">İptal</button>
                <button class="btn-primary" onclick="saveRecord()">💾 Kaydet</button>
            </div>
        </div>
    </div>

    <script>
        let allData = [];
        let selectedIds = new Set();
        let currentPage = 1;
        let totalRecords = 0;
        let categories = [];
        let searchTimeout = null;
        
        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', () => {
            loadCategories();
            loadData();
        });
        
        // Kategorileri yükle
        async function loadCategories() {
            try {
                const res = await fetch('api/categories');
                const data = await res.json();
                categories = data.categories;
                
                const select = document.getElementById('categoryFilter');
                const editSelect = document.getElementById('editCategory');
                
                categories.forEach(cat => {
                    select.innerHTML += `<option value="${cat.name}">${cat.name} (${cat.count.toLocaleString()})</option>`;
                    editSelect.innerHTML += `<option value="${cat.name}">${cat.name}</option>`;
                });
                
                document.getElementById('categoryCount').textContent = categories.length;
            } catch (e) {
                console.error('Kategori yükleme hatası:', e);
            }
        }
        
        // Debounce search
        function debounceSearch() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                currentPage = 1;
                loadData();
            }, 300);
        }
        
        // Verileri yükle
        async function loadData() {
            const search = document.getElementById('searchInput').value;
            const category = document.getElementById('categoryFilter').value;
            const limit = document.getElementById('limitSelect').value;
            const offset = (currentPage - 1) * parseInt(limit);
            
            document.getElementById('tableBody').innerHTML = '<tr><td colspan="6" class="loading">Yükleniyor</td></tr>';
            
            try {
                let url = `api/data?limit=${limit}&offset=${offset}`;
                if (search) url += `&search=${encodeURIComponent(search)}`;
                if (category) url += `&category=${encodeURIComponent(category)}`;
                
                const res = await fetch(url);
                const data = await res.json();
                
                allData = data.data;
                totalRecords = data.total;
                
                document.getElementById('totalCount').textContent = data.total.toLocaleString();
                document.getElementById('filteredCount').textContent = data.data.length.toLocaleString();
                
                const totalPages = Math.ceil(totalRecords / parseInt(limit));
                document.getElementById('currentPage').textContent = currentPage;
                document.getElementById('totalPages').textContent = totalPages || 1;
                
                document.getElementById('prevBtn').disabled = currentPage <= 1;
                document.getElementById('nextBtn').disabled = currentPage >= totalPages;
                
                renderTable();
            } catch (e) {
                console.error('Veri yükleme hatası:', e);
                document.getElementById('tableBody').innerHTML = '<tr><td colspan="6" class="empty-state">Veri yüklenemedi!</td></tr>';
            }
        }
        
        // Tabloyu render et
        function renderTable() {
            const tbody = document.getElementById('tableBody');
            
            if (allData.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="empty-state">Kayıt bulunamadı</td></tr>';
                return;
            }
            
            tbody.innerHTML = allData.map(row => {
                const isSelected = selectedIds.has(row.term_id);
                const catClass = 'cat-' + (row.category || '').replace(/[^a-z]/g, '-');
                
                return `
                    <tr class="${isSelected ? 'selected' : ''}" data-id="${row.term_id}">
                        <td class="checkbox-cell">
                            <input type="checkbox" ${isSelected ? 'checked' : ''} onchange="toggleSelect(${row.term_id})">
                        </td>
                        <td>${escapeHtml(row.canonical_en || '')}</td>
                        <td>${escapeHtml(row.canonical_tr || '')}</td>
                        <td><span class="category-badge ${catClass}">${row.category || '-'}</span></td>
                        <td>${row.confidence_score ? row.confidence_score.toFixed(2) : '-'}</td>
                        <td class="actions-cell">
                            <button class="btn-edit" onclick="openEditModal(${row.term_id})">✏️</button>
                        </td>
                    </tr>
                `;
            }).join('');
            
            updateSelectionUI();
        }
        
        // HTML escape
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Seçim toggle
        function toggleSelect(id) {
            if (selectedIds.has(id)) {
                selectedIds.delete(id);
            } else {
                selectedIds.add(id);
            }
            updateSelectionUI();
            renderTable();
        }
        
        // Tümünü seç/kaldır
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll').checked;
            
            if (selectAll) {
                allData.forEach(row => selectedIds.add(row.term_id));
            } else {
                allData.forEach(row => selectedIds.delete(row.term_id));
            }
            
            updateSelectionUI();
            renderTable();
        }
        
        // Seçim UI güncelle
        function updateSelectionUI() {
            const count = selectedIds.size;
            const info = document.getElementById('selectionInfo');
            const btn = document.getElementById('deleteSelectedBtn');
            
            if (count > 0) {
                info.style.display = 'inline-block';
                btn.style.display = 'inline-block';
                document.getElementById('selectedCount').textContent = count;
            } else {
                info.style.display = 'none';
                btn.style.display = 'none';
            }
        }
        
        // Seçilenleri sil
        async function deleteSelected() {
            if (selectedIds.size === 0) return;
            
            if (!confirm(`${selectedIds.size} kayıt silinecek. Emin misiniz?`)) return;
            
            try {
                const res = await fetch('api/delete', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ ids: Array.from(selectedIds) })
                });
                
                const data = await res.json();
                
                if (data.success) {
                    showToast(`${data.deleted} kayıt silindi`, 'success');
                    selectedIds.clear();
                    loadData();
                    loadCategories();
                } else {
                    showToast('Silme hatası: ' + data.error, 'error');
                }
            } catch (e) {
                showToast('Silme hatası!', 'error');
            }
        }
        
        // Edit modal aç
        function openEditModal(id) {
            const row = allData.find(r => r.term_id === id);
            if (!row) return;
            
            document.getElementById('modalTitle').textContent = 'Kayıt Düzenle';
            document.getElementById('editId').value = id;
            document.getElementById('editEn').value = row.canonical_en || '';
            document.getElementById('editTr').value = row.canonical_tr || '';
            document.getElementById('editCategory').value = row.category || '';
            document.getElementById('editConfidence').value = row.confidence_score || '0.9';
            
            document.getElementById('modal').classList.add('active');
        }
        
        // Add modal aç
        function openAddModal() {
            document.getElementById('modalTitle').textContent = 'Yeni Kayıt Ekle';
            document.getElementById('editId').value = '';
            document.getElementById('editEn').value = '';
            document.getElementById('editTr').value = '';
            document.getElementById('editCategory').value = categories[0]?.name || '';
            document.getElementById('editConfidence').value = '0.9';
            
            document.getElementById('modal').classList.add('active');
        }
        
        // Modal kapat
        function closeModal() {
            document.getElementById('modal').classList.remove('active');
        }
        
        // Kaydet
        async function saveRecord() {
            const id = document.getElementById('editId').value;
            const data = {
                canonical_en: document.getElementById('editEn').value.trim(),
                canonical_tr: document.getElementById('editTr').value.trim(),
                category: document.getElementById('editCategory').value,
                confidence_score: parseFloat(document.getElementById('editConfidence').value) || 0.9
            };
            
            if (!data.canonical_en) {
                showToast('İngilizce terim gerekli!', 'error');
                return;
            }
            
            try {
                let url = id ? `api/update/${id}` : 'api/add';
                const res = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                
                const result = await res.json();
                
                if (result.success) {
                    showToast(id ? 'Kayıt güncellendi' : 'Kayıt eklendi', 'success');
                    closeModal();
                    loadData();
                } else {
                    showToast('Hata: ' + result.error, 'error');
                }
            } catch (e) {
                showToast('İşlem hatası!', 'error');
            }
        }
        
        // Sayfalama
        function prevPage() {
            if (currentPage > 1) {
                currentPage--;
                loadData();
            }
        }
        
        function nextPage() {
            const limit = parseInt(document.getElementById('limitSelect').value);
            const totalPages = Math.ceil(totalRecords / limit);
            if (currentPage < totalPages) {
                currentPage++;
                loadData();
            }
        }
        
        // Toast mesajı
        function showToast(message, type = 'success') {
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            toast.textContent = message;
            document.body.appendChild(toast);
            
            setTimeout(() => toast.remove(), 3000);
        }
        
        // ESC ile modal kapat
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape') closeModal();
        });
    </script>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/api/categories')
def get_categories():
    try:
        conn = get_db()
        cursor = conn.cursor()
        cursor.execute('''
            SELECT category, COUNT(*) as cnt 
            FROM technical_terms 
            GROUP BY category 
            ORDER BY cnt DESC
        ''')
        categories = [{'name': row['category'], 'count': row['cnt']} for row in cursor.fetchall()]
        conn.close()
        return jsonify({'categories': categories})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/data')
def get_data():
    try:
        limit = request.args.get('limit', 100, type=int)
        offset = request.args.get('offset', 0, type=int)
        search = request.args.get('search', '')
        category = request.args.get('category', '')
        
        conn = get_db()
        cursor = conn.cursor()
        
        # Build query
        where_clauses = []
        params = []
        
        if search:
            where_clauses.append('(canonical_en LIKE ? OR canonical_tr LIKE ?)')
            params.extend([f'%{search}%', f'%{search}%'])
        
        if category:
            where_clauses.append('category = ?')
            params.append(category)
        
        where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
        
        # Get total count
        cursor.execute(f'SELECT COUNT(*) FROM technical_terms {where_sql}', params)
        total = cursor.fetchone()[0]
        
        # Get data
        cursor.execute(f'''
            SELECT term_id, canonical_en, canonical_tr, category, confidence_score, created_at
            FROM technical_terms 
            {where_sql}
            ORDER BY created_at DESC
            LIMIT ? OFFSET ?
        ''', params + [limit, offset])
        
        data = [dict(row) for row in cursor.fetchall()]
        conn.close()
        
        return jsonify({'data': data, 'total': total})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/add', methods=['POST'])
def add_record():
    try:
        data = request.get_json()
        
        conn = get_db()
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO technical_terms (canonical_en, canonical_tr, category, confidence_score)
            VALUES (?, ?, ?, ?)
        ''', (
            data.get('canonical_en'),
            data.get('canonical_tr'),
            data.get('category'),
            data.get('confidence_score', 0.9)
        ))
        conn.commit()
        new_id = cursor.lastrowid
        conn.close()
        
        return jsonify({'success': True, 'id': new_id})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/update/<int:term_id>', methods=['POST'])
def update_record(term_id):
    try:
        data = request.get_json()
        
        conn = get_db()
        cursor = conn.cursor()
        cursor.execute('''
            UPDATE technical_terms 
            SET canonical_en = ?, canonical_tr = ?, category = ?, confidence_score = ?
            WHERE term_id = ?
        ''', (
            data.get('canonical_en'),
            data.get('canonical_tr'),
            data.get('category'),
            data.get('confidence_score', 0.9),
            term_id
        ))
        conn.commit()
        conn.close()
        
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/delete', methods=['POST'])
def delete_records():
    try:
        data = request.get_json()
        ids = data.get('ids', [])
        
        if not ids:
            return jsonify({'success': False, 'error': 'No IDs provided'})
        
        conn = get_db()
        cursor = conn.cursor()
        
        placeholders = ','.join(['?' for _ in ids])
        cursor.execute(f'DELETE FROM technical_terms WHERE term_id IN ({placeholders})', ids)
        deleted = cursor.rowcount
        conn.commit()
        conn.close()
        
        return jsonify({'success': True, 'deleted': deleted})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
