const cluster = require('cluster');
const os = require('os');
const path = require('path');
const http = require('http'); 
const fs = require('fs');
require('dotenv').config({ path: path.resolve(__dirname, '.env') });

const NUM_CPUS = os.cpus().length;
const port = process.env.PORT || 3000;
const proxyUrl = process.env.PROXY_URL;


const pingSearchEngines = () => { 
    if (!proxyUrl || proxyUrl.includes('localhost')) {
        console.warn('[Indexing] Ping diabaikan: PROXY_URL tidak disetel atau menggunakan localhost.');
        return;
    }
    
    const sitemapUrl = encodeURIComponent(`${proxyUrl}/sitemap.xml`);

    const googlePing = `http://www.google.com/ping?sitemap=${sitemapUrl}`;
    http.get(googlePing, (res) => {
        console.log(`[Indexing] Ping Google berhasil. Status: ${res.statusCode}`);
    }).on('error', (e) => {
        console.error(`[Indexing] Gagal ping Google: ${e.message}`);
    });

    const bingPing = `http://www.bing.com/ping?sitemap=${sitemapUrl}`;
    http.get(bingPing, (res) => {
        console.log(`[Indexing] Ping Bing berhasil. Status: ${res.statusCode}`);
    }).on('error', (e) => {
        console.error(`[Indexing] Gagal ping Bing: ${e.message}`);
    });
};

const loadAds = () => {
    let ads = [];
    try {
        const adsData = fs.readFileSync(path.join(__dirname, 'ads.json'), 'utf8'); 
        ads = JSON.parse(adsData);
    } catch (err) {
        console.error('Gagal memuat skrip iklan dan analitik dari ads.json:', err.message);
    }

    const headerAds = ads.filter(ad => ad.type === 'header').map(ad => ad.script).join('');
    const bodyAds = ads.filter(ad => ad.type === 'body').map(ad => ad.script).join('');

    return { headerAds, bodyAds };
};


if (cluster.isMaster) { 
    console.log(`Master process ${process.pid} is running. Total CPU cores: ${NUM_CPUS}`);

    console.log('[Indexing] Melakukan ping otomatis ke mesin pencari...');
    pingSearchEngines();

    for (let i = 0; i < NUM_CPUS; i++) {
        cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} died (Code: ${code}, Signal: ${signal}). Starting a new worker...`);
        cluster.fork(); 
    });
} else {

    const express = require('express');

    const assetProxy = require('./src/middleware/assetProxy'); 
    const apiProxy = require('./src/middleware/apiProxy');
    const bookmarkRoute = require('./src/routes/bookmarkRoute');
    const mainProxyRoute = require('./src/routes/mainProxy');
    const seoRoute = require('./src/routes/seoRoute'); 
    const asyncProxy = require('./src/routes/asyncProxy').router; 

    const app = express();

    const adsScripts = loadAds();
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());

    app.use((req, res, next) => {
        req.adsScripts = adsScripts; 
        next();
    });

    app.use(assetProxy); 
    app.use(apiProxy);
    app.use(bookmarkRoute);
    
    app.use(seoRoute); 
    
    app.use(asyncProxy);
    
    app.use(mainProxyRoute);

    app.listen(port, () => {
        console.log(`Worker ${process.pid} started and listening on port ${port}.`);
        console.log(`Akses: ${proxyUrl}`);
    });
}
