var express = require('express');
var router = express.Router();
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');
const { logger } = require('nodejs-log-agent');
const moment = require('moment');
const { getFormattedDateForLogFile } = require('../utils/dateHelper');
const { readLogsByDate } = require('../services/logService');
const cronJob = require('../libs/cronJob'); // Impor modul cron job
const invoiceController = require('../controllers/invoiceController');
/**
 * Potong pesan log menjadi maksimal 100 kata
 */
function truncateMessage(message, maxWords = 10) {
    const words = message.split(/\s+/);
    return words.length > maxWords
        ? words.slice(0, maxWords).join(' ') + '...'
        : message;
}

async function generateSimulatedData(category) {
    let simulatedLogs = [];
    const now = new Date();

    // Set waktu awal ke 00:00:00
    const startDate = new Date(now);
    startDate.setHours(0, 0, 0, 0);

    // Set waktu akhir ke 23:59:59
    const endDate = new Date(now);
    endDate.setHours(23, 59, 59, 999);

    const dateString = getFormattedDateForLogFile(startDate);
    const allLogsToday = await readLogsByDate(dateString);

    // Filter log berdasarkan kategori untuk memisahkan aktivitas
    const cronKeywords = ['[Cron Job]', '[Batch Processor]', '[Batch]', '[Send Message]', '[DB]'];
    if (category === 'Pengiriman Invoice') {
        simulatedLogs = allLogsToday.filter(log => 
            cronKeywords.some(keyword => log.message.startsWith(keyword))
        );
    } else { // Asumsikan kategori lain adalah 'API'
        simulatedLogs = allLogsToday.filter(log => 
            !cronKeywords.some(keyword => log.message.startsWith(keyword))
        );
    }

    // Convert all timestamps to Date objects
    const parsedLogs = simulatedLogs.map(log => ({
        ...log,
        // Beberapa log mungkin memiliki format timestamp yang berbeda, normalisasi di sini
        // Contoh: '2024-05-26 10:30:00' -> '2024-05-26T10:30:00'
        timestamp: new Date(log.timestamp.replace(' ', 'T'))
    }));

    // Sort logs by timestamp ascending
    parsedLogs.sort((a, b) => a.timestamp - b.timestamp);

    // Group logs into 30-minute intervals
    const groupedData = [];
    let intervalStart = new Date(startDate);
    const intervalDuration = 30 * 60 * 1000; // 30 minutes

    while (intervalStart < endDate) {
        const intervalEnd = new Date(intervalStart.getTime() + intervalDuration);
        const logsInInterval = parsedLogs.filter(log =>
            log.timestamp >= intervalStart && log.timestamp < intervalEnd
        );

        let overallStatus = 'info';
        const details = [];

        if (logsInInterval.some(log => log.level === 'error')) {
            overallStatus = 'error';
        } else if (logsInInterval.some(log => log.level === 'warn')) {
            overallStatus = 'warn';
        }

        const uniqueInfoMessages = new Set();
        logsInInterval.forEach(log => {
            const truncated = truncateMessage(log.message);
            if (log.level === 'info') {

                if (!uniqueInfoMessages.has(log.level)) {
                    details.push({
                        level: log.level,
                        message: "Sistem berjalan dengan baik",
                        timestamp: log.timestamp
                    });
                    uniqueInfoMessages.add(log.level);
                }
            } else {
                details.push({
                    level: log.level,
                    message: truncated,
                    timestamp: log.timestamp
                });
            }
        });

        if (details.length === 0) {
            details.push({
                level: 'future',
                message: `${category} - Tidak ada aktivitas log.`,
                timestamp: new Date(intervalStart)
            });
            overallStatus = 'future';
        }

        groupedData.push({
            timestamp: new Date(intervalStart),
            status: overallStatus,
            details: details
        });

        intervalStart = new Date(intervalStart.getTime() + intervalDuration);
    }

    // Convert to JSON-safe format
    return groupedData.map(item => ({
        ...item,
        timestamp: item.timestamp.toISOString(),
        details: item.details.map(d => ({
            ...d,
            timestamp: d.timestamp.toISOString()
        }))
    }));
}

/* GET health status. */
router.get('/health', require('../controllers/healthController').checkHealth);

/* GET home page. */
router.get('/', async function(req, res, next) {
    // Generate data for both API and Invoice categories
    const apiData = await generateSimulatedData('API');
    const invoiceData = await generateSimulatedData('Pengiriman Invoice');
    // Get the IP address from the request object
    // req.ip might return '::1' for localhost or IPv6 addresses.
    // For more robust IP detection in production (behind proxies/load balancers),
    // you might need to check req.headers['x-forwarded-for'].
    const ipAddress = req.ip || 'Tidak Diketahui';

    // Get the User-Agent string from the request headers
    const userAgent = req.headers['user-agent'] || 'Tidak Diketahui';
    // --- Basic User-Agent Parsing (Simplified for demonstration) ---
    // In a real application, consider using a dedicated library like 'ua-parser-js'
    // or 'express-useragent' for more accurate and comprehensive parsing.

    let browser = 'Tidak Diketahui';
    let os = 'Tidak Diketahui';
    let deviceType = 'Desktop';

    if (userAgent.includes('Chrome') && !userAgent.includes('Edge')) {
        browser = 'Chrome';
    } else if (userAgent.includes('Firefox')) {
        browser = 'Firefox';
    } else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
        browser = 'Safari';
    } else if (userAgent.includes('MSIE') || userAgent.includes('Trident')) {
        browser = 'Internet Explorer';
    } else if (userAgent.includes('Edge')) {
        browser = 'Edge';
    }

    if (userAgent.includes('Windows')) {
        os = 'Windows';
    } else if (userAgent.includes('Macintosh') || userAgent.includes('Mac OS')) {
        os = 'macOS';
    } else if (userAgent.includes('Linux')) {
        os = 'Linux';
    } else if (userAgent.includes('Android')) {
        os = 'Android';
        deviceType = 'Mobile';
    } else if (userAgent.includes('iPhone') || userAgent.includes('iPad')) {
        os = 'iOS';
        deviceType = 'Mobile'; // Or 'Tablet' for iPad
    }

    // Pass the extracted information to the EJS template
    res.render('index', {
        ipAddress: ipAddress,
        browsers: browser,
        os: os,
        deviceType: deviceType,
        date : moment().format("dddd, DD MMMM YYYY"),
        status : cronJob.getDesiredState() ? "Aktif" : "Berhenti",
        apiData: apiData, 
        invoiceData: invoiceData,
        // Data baru untuk kartu kontrol cron
        cron: {
            schedulerStatus: cronJob.getStatus(),
            desiredState: cronJob.getDesiredState(),
            isExecuting: cronJob.isTaskRunning(),
            timestamps: cronJob.getTimestamps()
        }
    });
  logger.info('Index Page', { message: `Index Page di akses oleh ${req.ip}` });
});

router.get('/changelog', invoiceController.showChangelog);

module.exports = router;
