import express from 'express';
import { createProxyServer } from 'http-proxy';
import zlib from 'zlib';
import fs from 'fs';
import path from 'path';

let originalUrl: string | undefined  = undefined;

const app = express();
const proxy = createProxyServer({
  target: 'http://google.com', // Replace with your target URL
  changeOrigin: true,
  // ignorePath: true,
  selfHandleResponse: true, // Required for modifying the response
});


proxy.on('proxyReq', (proxyReq, req) => {
  // Forward necessary headers
  proxyReq.setHeader('User-Agent', req.headers['user-agent'] || '');
  proxyReq.setHeader('Accept-Language', req.headers['accept-language'] || '');
  proxyReq.setHeader('Cookie', req.headers['cookie'] || ''); // Ensure cookies are forwarded
});

proxy.on('proxyRes', (proxyRes, req, res) => {
  let body: Buffer[] = [];

  proxyRes.on('data', (chunk) => {
    body.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  });

  proxyRes.on('end', () => {
    let rawBody = Buffer.concat(body);

    // Handle decompression safely
    try {
      if (proxyRes.headers['content-encoding']) {
        if (proxyRes.headers['content-encoding'].includes('gzip')) {
          rawBody = zlib.gunzipSync(rawBody);
        } else if (proxyRes.headers['content-encoding'].includes('br')) {
          rawBody = zlib.brotliDecompressSync(rawBody);
        } else if (proxyRes.headers['content-encoding'].includes('deflate')) {
          rawBody = zlib.inflateSync(rawBody);
        }

        delete proxyRes.headers['content-encoding']; // Let the browser handle plain text
      }
    } catch (err) {
      console.error('Decompression failed:', err);
    }

    // Modify HTML only
    const contentType = proxyRes.headers['content-type'] || '';
    if (contentType.includes('text/html')) {
      let response = rawBody.toString('utf8');
      const filePath = path.join(__dirname, 'original_response.html');
      fs.writeFile(filePath, response, (err) => {
        if (err) {
            console.error('Error writing to file', err);
          }
        console.error('Successtully writing response to file', err);
    });

    // Debugging
    console.log("Received HTML Length:", response.length);


      // const oU = originalUrl || 'https://www.bosch-diy.com';
      const oU = 'https://www.bosch-diy.com';
      // Add a <base> tag to ensure relative URLs resolve correctly
      response = response.replace(/<head>/, `<head><base href="${oU}">`);

      // Rewrite only relative URLs to absolute URLs
      response = response.replace(/(href|src)="\/([^"]+)"/g, `$1="${oU}/$2"`);

      rawBody = Buffer.from(response, 'utf8');
    }

    // 🔹 Set CORS headers dynamically for all responses
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    res.setHeader('Pragma', 'no-cache');
    res.setHeader('Expires', '0');

    res.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
    res.end(rawBody);
  });
});





app.get('/proxy', (req, res) => {
  const oU = req.query.url;
  console.log('originalUrl:', oU)
  if (!oU || typeof oU !== 'string') {
    return res.status(400).send('Please provide a valid URL as a string');
  }
  originalUrl = oU;

  req.url = req.url.replace(/^\/proxy/, '/search');
  console.log('req.url:', req.url)

  // console.log('proxy:', proxy)
  proxy.web(req, res, { target: originalUrl });
});

const port = process.env.PORT || 3005;

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});