const express = require('express');
const cors = require('cors'); // Import the cors package
const app = express();
const PORT = 3003;

// Enable CORS for all routes
app.use(cors());

const statusColors = {
    up: 'green',
    down: 'red',
    pending: 'orange',
    maintenance: 'gray',
    unknown: 'orange'
};

const API_KEY = 'uk1_Z42lkd61abHwZmVMqj_6PUoXxeMboTnO6lXCa4yi';
const METRICS_URL = 'http://192.168.12.126:6789/https://status.swightshome.xyz/metrics';

let fetch;

// Dynamically import node-fetch
import('node-fetch').then(module => {
    fetch = module.default;
}).catch(err => {
    console.error('Error importing node-fetch:', err);
    process.exit(1);
});

// Set Content Security Policy header
app.use((req, res, next) => {
    res.setHeader(
        'Content-Security-Policy',
        "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:;"
    );
    next();
});

// Root route
app.get('/', (req, res) => {
    res.redirect('/status'); // Redirect root to /status
});

async function fetchMetrics() {
    try {
        const response = await fetch(METRICS_URL, {
            headers: {
                'Authorization': `Basic ${Buffer.from(`:${API_KEY}`).toString('base64')}`,
                                     'Origin': 'https://swightshome.xyz'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.text();
        return data;
    } catch (error) {
        console.error('Error fetching metrics:', error);
        return null;
    }
}

function parseMetrics(metrics) {
    const statusMap = {};
    const lines = metrics.split('\n');

    lines.forEach(line => {
        if (line.startsWith('monitor_status{')) {
            const monitorNameMatch = line.match(/monitor_name="([^"]+)"/);
            const statusMatch = line.match(/\s(\d+)$/);

            if (monitorNameMatch && statusMatch) {
                const monitorName = monitorNameMatch[1];
                const status = parseInt(statusMatch[1], 10);
                statusMap[monitorName] = status;
            }
        }
    });

    return statusMap;
}

app.get('/status', async (req, res) => {
    const metrics = await fetchMetrics();

    if (!metrics) {
        res.status(500).json({ error: 'Uptime Kuma is not responding.' });
        return;
    }

    const statusMap = parseMetrics(metrics);
    res.json(statusMap); // Send JSON response
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
