const express = require('express');
const path = require('path');
const cors = require('cors');
const http = require('http');
const https = require('https');
const { spawn } = require('child_process');
const zlib = require('zlib');
const app = express();
const PORT = 3000;

// Middleware
app.use(cors());
app.use(express.json());

// Static file serving
app.use(express.static('.'));
app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use('/images', express.static('images'));

// Serve new app/demo/admin workspaces with simple auth shim
const appWorkspace = path.join(__dirname, 'domains/app');
const demoWorkspace = path.join(__dirname, 'domains/demo');
const mainWorkspace = path.join(__dirname, 'domains/main');
const adminWorkspace = path.join(__dirname, 'domains/admin');

// In production you can swap this with real authentication middleware
const authGuard = (req, res, next) => {
    if (process.env.APP_TOKEN && req.headers['x-app-token'] !== process.env.APP_TOKEN) {
        return res.status(401).send('App workspace locked. Provide X-App-Token header.');
    }
    next();
};

const staticOptions = { extensions: ['html'] };

app.use('/app', authGuard, express.static(appWorkspace, staticOptions));
app.use('/demo', express.static(demoWorkspace, staticOptions));
app.use('/domains/main', express.static(mainWorkspace, staticOptions));
app.use('/admin', express.static(adminWorkspace, staticOptions));

const BROWSER_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive'
};

function decompressBody(buffer, encoding = '') {
    const enc = (encoding || '').toLowerCase();
    try {
        if (enc.includes('br')) {
            return zlib.brotliDecompressSync(buffer);
        }
        if (enc.includes('gzip')) {
            return zlib.gunzipSync(buffer);
        }
        if (enc.includes('deflate')) {
            return zlib.inflateSync(buffer);
        }
    } catch (error) {
        console.warn('[email-finder] decompress failed', enc, error?.message || error);
    }
    return buffer;
}

function fetchRemoteContent(url, redirects = 0) {
    return new Promise((resolve, reject) => {
        if (redirects > 5) {
            reject(new Error('Too many redirects'));
            return;
        }
        const client = url.startsWith('https://') ? https : http;
        const request = client.get(url, { headers: BROWSER_HEADERS }, (response) => {
            const { statusCode, headers } = response;
            if (statusCode >= 300 && statusCode < 400 && headers.location) {
                response.resume();
                const nextUrl = new URL(headers.location, url).href;
                fetchRemoteContent(nextUrl, redirects + 1).then(resolve).catch(reject);
                return;
            }
            if (statusCode >= 400) {
                response.resume();
                reject(new Error(`Remote HTTP ${statusCode}`));
                return;
            }
            const chunks = [];
            response.on('data', (chunk) => {
                chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
            });
            response.on('end', () => {
                const buffer = Buffer.concat(chunks);
                const body = decompressBody(buffer, headers['content-encoding']);
                resolve({ body: body.toString('utf8'), headers });
            });
        });
        request.on('error', reject);
        request.setTimeout(15000, () => {
            request.destroy(new Error('Remote fetch timeout'));
        });
    });
}

app.get('/api/email-finder', async (req, res) => {
    const target = req.query.url;
    if (!target) {
        res.json({ success: false, error: 'Missing url parameter' });
        return;
    }
    let parsed;
    try {
        parsed = new URL(target);
    } catch (error) {
        res.json({ success: false, error: 'Invalid url parameter' });
        return;
    }

    try {
        const { body } = await fetchRemoteContent(parsed.href);
        res.json({ success: true, content: body });
    } catch (error) {
        res.json({ success: false, error: error.message || 'Unable to fetch target' });
    }
});

app.get('/app/*', authGuard, (req, res) => {
    const file = req.path.replace('/app/', '').replace(/\/$/, '');
    const target = file ? path.join(appWorkspace, file, 'index.html') : path.join(appWorkspace, 'index.html');
    res.sendFile(target);
});

app.get('/demo/*', (req, res) => {
    const file = req.path.replace('/demo/', '').replace(/\/$/, '');
    const target = file ? path.join(demoWorkspace, file, 'index.html') : path.join(demoWorkspace, 'index.html');
    res.sendFile(target);
});

app.get('/main/*', (req, res) => {
    const file = req.path.replace('/main/', '').replace(/\/$/, '');
    const target = file ? path.join(mainWorkspace, file) : path.join(mainWorkspace, 'index.html');
    res.sendFile(target);
});

app.get('/admin/*', (req, res) => {
    const file = req.path.replace('/admin/', '').replace(/\/$/, '');
    const target = file ? path.join(adminWorkspace, file, 'index.html') : path.join(adminWorkspace, 'index.html');
    res.sendFile(target);
});

// Serve primary tools
app.get('/', (req, res) => {
    res.sendFile(path.join(mainWorkspace, 'index.html'));
});

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

app.get('/google-maps', (req, res) => {
    res.sendFile(path.join(__dirname, 'google-map-scraper.html'));
});

app.get('/user_info.php', (req, res) => {
    res.json({
        authenticated: true,
        name: 'Local User',
        email: 'local@example.com',
        phone: '+1234567890',
        plan: 'Local Development'
    });
});

// Debug endpoint
app.get('/debug', (req, res) => {
    res.sendFile(path.join(__dirname, 'debug.html'));
});

// Start server
app.listen(PORT, () => {
    console.log(`🚀 Local server running at http://localhost:${PORT}`);
    console.log(`🌐 Main marketing site:   http://localhost:${PORT}/domains/main/`);
    console.log(`🧰 App workspace:         http://localhost:${PORT}/app/ (requires X-App-Token if set)`);
    console.log(`🧪 Demo workspace:        http://localhost:${PORT}/demo/`);
    console.log(`🛡️ Admin console:         http://localhost:${PORT}/admin/`);
    console.log(`🗺️  Google Maps Scraper:   http://localhost:${PORT}/google-maps`);
    console.log(`🔍 Debug tool:            http://localhost:${PORT}/debug`);
    console.log(`📋 Chrome Extension files are in this directory for installation`);
});

// Handle graceful shutdown
process.on('SIGINT', () => {
    console.log('\n🛑 Shutting down server...');
    process.exit(0);
});
