const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs-extra');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));

// Serve static files
app.use(express.static(path.join(__dirname)));

// Database file path
const DB_FILE = path.join(__dirname, 'kthc-qa-database.json');
const BACKUP_DIR = path.join(__dirname, 'backups');

// Ensure backup directory exists
fs.ensureDirSync(BACKUP_DIR);

// Routes
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'qa-manager.html'));
});

app.get('/demo', (req, res) => {
    res.sendFile(path.join(__dirname, 'qa-demo.html'));
});

app.get('/test', (req, res) => {
    res.sendFile(path.join(__dirname, 'qa-test.html'));
});

// API Routes
app.get('/api/qa-data', async (req, res) => {
    try {
        if (await fs.pathExists(DB_FILE)) {
            const data = await fs.readJson(DB_FILE);
            res.json(data);
        } else {
            res.json({ kthc_qa_database: [] });
        }
    } catch (error) {
        console.error('Error reading QA data:', error);
        res.status(500).json({ error: 'Lỗi khi đọc dữ liệu' });
    }
});

app.post('/api/save-qa-data', async (req, res) => {
    try {
        const { kthc_qa_database, metadata } = req.body;
        
        // Validate data
        if (!Array.isArray(kthc_qa_database)) {
            return res.status(400).json({ error: 'Dữ liệu không hợp lệ' });
        }

        // Create backup before saving
        if (await fs.pathExists(DB_FILE)) {
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const backupFile = path.join(BACKUP_DIR, `backup-${timestamp}.json`);
            await fs.copy(DB_FILE, backupFile);
        }

        // Save new data
        const dataToSave = {
            kthc_qa_database,
            metadata: {
                ...metadata,
                last_updated: new Date().toISOString(),
                total_questions: kthc_qa_database.length
            }
        };

        await fs.writeJson(DB_FILE, dataToSave, { spaces: 2 });
        
        res.json({ 
            success: true, 
            message: 'Dữ liệu đã được lưu thành công',
            total_questions: kthc_qa_database.length
        });
    } catch (error) {
        console.error('Error saving QA data:', error);
        res.status(500).json({ error: 'Lỗi khi lưu dữ liệu' });
    }
});

app.post('/api/create-backup', async (req, res) => {
    try {
        const { kthc_qa_database, backup_info } = req.body;
        
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const backupFile = path.join(BACKUP_DIR, `manual-backup-${timestamp}.json`);
        
        const backupData = {
            kthc_qa_database,
            backup_info: {
                ...backup_info,
                created_at: new Date().toISOString(),
                backup_type: 'manual'
            }
        };

        await fs.writeJson(backupFile, backupData, { spaces: 2 });
        
        res.json({ 
            success: true, 
            message: 'Backup đã được tạo thành công',
            backup_file: path.basename(backupFile)
        });
    } catch (error) {
        console.error('Error creating backup:', error);
        res.status(500).json({ error: 'Lỗi khi tạo backup' });
    }
});

app.get('/api/backups', async (req, res) => {
    try {
        const files = await fs.readdir(BACKUP_DIR);
        const backups = [];
        
        for (const file of files) {
            if (file.endsWith('.json')) {
                const filePath = path.join(BACKUP_DIR, file);
                const stats = await fs.stat(filePath);
                backups.push({
                    filename: file,
                    size: stats.size,
                    created_at: stats.birthtime,
                    modified_at: stats.mtime
                });
            }
        }
        
        res.json({ backups: backups.sort((a, b) => b.modified_at - a.modified_at) });
    } catch (error) {
        console.error('Error listing backups:', error);
        res.status(500).json({ error: 'Lỗi khi liệt kê backups' });
    }
});

app.get('/api/backup/:filename', async (req, res) => {
    try {
        const { filename } = req.params;
        const backupFile = path.join(BACKUP_DIR, filename);
        
        if (await fs.pathExists(backupFile)) {
            const data = await fs.readJson(backupFile);
            res.json(data);
        } else {
            res.status(404).json({ error: 'Backup không tồn tại' });
        }
    } catch (error) {
        console.error('Error reading backup:', error);
        res.status(500).json({ error: 'Lỗi khi đọc backup' });
    }
});

app.get('/api/stats', async (req, res) => {
    try {
        if (await fs.pathExists(DB_FILE)) {
            const data = await fs.readJson(DB_FILE);
            const qaData = data.kthc_qa_database || [];
            
            const categories = new Set(qaData.map(qa => qa.category));
            const allKeywords = qaData.flatMap(qa => qa.keywords || []);
            const uniqueKeywords = new Set(allKeywords);
            
            const stats = {
                totalQuestions: qaData.length,
                totalCategories: categories.size,
                totalKeywords: uniqueKeywords.size,
                categories: Array.from(categories),
                lastUpdated: data.metadata?.last_updated || null
            };
            
            res.json(stats);
        } else {
            res.json({
                totalQuestions: 0,
                totalCategories: 0,
                totalKeywords: 0,
                categories: [],
                lastUpdated: null
            });
        }
    } catch (error) {
        console.error('Error getting stats:', error);
        res.status(500).json({ error: 'Lỗi khi lấy thống kê' });
    }
});

// Health check endpoint
app.get('/api/health', (req, res) => {
    res.json({ 
        status: 'OK', 
        timestamp: new Date().toISOString(),
        version: '1.0.0'
    });
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error('Server error:', err);
    res.status(500).json({ error: 'Lỗi server nội bộ' });
});

// 404 handler
app.use((req, res) => {
    res.status(404).json({ error: 'Không tìm thấy trang' });
});

// Start server
app.listen(PORT, () => {
    console.log(`🚀 Server đang chạy trên port ${PORT}`);
    console.log(`📚 QA Manager: http://localhost:${PORT}`);
    console.log(`🎯 Demo: http://localhost:${PORT}/demo`);
    console.log(`🔍 Test: http://localhost:${PORT}/test`);
    console.log(`📊 API: http://localhost:${PORT}/api/health`);
});

module.exports = app;

