import http,{ IncomingMessage, ServerResponse, request as httpRequest } from 'http';
import https, { request as httpsRequest } from 'https';
import { ClientRequest as ProxyRequest, IncomingMessage as ProxyResponse } from 'http';
import { Response } from 'express';
import zlib from 'zlib';
import fs, { write } from 'fs';
import path from 'path';
import { directSimpleRewriteLinks, getBaseUrl, simpleRewriteLinks } from '../helpers/helpers';
import cookieParser from 'cookie-parser';
import { getPublicHost } from '../helpers/getPublicHost';
import { writeToLog } from '../helpers/writeToLog';
import { val } from 'cheerio/dist/commonjs/api/attributes';
import { writer } from 'repl';

const MAX_REDIRECTS = 5;

export const directReqHandler = (req: IncomingMessage, proxyReq: ProxyRequest) => {
    // Forward necessary headers for requests to the target URL
    // proxyReq.setHeader('Host', 'booking.com');
    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
    // req.headers['host'] = 'booking.com';
    // req.headers['host'] = 'localhost:3005';
    if (req.headers['set-cookie']) {
      writeToLog(`>> FOUND Set-Cookie in request: ${req.headers['set-cookie']}`);
    } else {
      // writeToLog(`>> NOT FOUND Set-Cookie in request, all req headers: ${JSON.stringify(req.headers)}`);
      writeToLog(`>> NOT FOUND Set-Cookie in request, all req headers:`);
      // const skipHeader = ['accept', 'cookie', 'accept-encoding'];
      const skipHeader: any = ['host'];
      // const skipHeader: any = [];
      Object.entries(req.headers).forEach(([key, value]) => {
        if (skipHeader.includes(key.toLowerCase())) {
          writeToLog(`>>>>>>>>>>>>>>>>>>>>>`);
          writeToLog(`>> SKIPPING ${key}, ${value}`);
          writeToLog(`>>>>>>>>>>>>>>>>>>>>>`);
          // writeToLog(`FOUND ${key}!`);
          // value = typeof value === 'string' ? value?.replace('https://booking.com', getPublicHost('basePath')) : '';
          // value = typeof value === 'string' ? value?.replace('https://account.booking.com', getPublicHost('basePath')) : '';
          // // req.headers[key] = value;
          // proxyReq.setHeader(key, (value as string) || '');
        } else if (key.toLowerCase() === 'host') {
          // value = typeof value === 'string' ? value?.replace('https://booking.com', getPublicHost('basePath')) : '';
          // value = typeof value === 'string' ? value?.replace('https://account.booking.com', getPublicHost('basePath')) : '';
          // writeToLog(`manipulating HOST setting it to ${value}`);
          // proxyReq.setHeader('host', value);
        } else if (key.toLowerCase() === 'referer') {
          if(req.method === 'GET') {
            const referer = req.headers ? encodeURIComponent(req.headers['referer'] || '') : '';
            writeToLog(`manipulating referrerm setting it to ${referer.replace('uri=', `uri=${encodeURIComponent(referer)}` || '')}`);
            console.log(`manipulating referrerm setting it to ${referer.replace('uri=', `uri=${encodeURIComponent(referer)}` || '')}`);
            proxyReq.setHeader('referer', referer.replace('uri=', `uri=${encodeURIComponent(referer)}` || ''));
          } else {
            let v = value as string || ''
            v = v.replace(getPublicHost('basePath'), `https://account.booking.com`);
            writeToLog(`manipulating referer, setting it to ${v}`);
            proxyReq.setHeader(key, v);
          }
          
        } else if(key.toLowerCase() === 'origin') {
          let v = value as string || ''
          v = v.replace(getPublicHost('basePath'), `https://account.booking.com`);
          writeToLog(`manipulating origin, setting it to ${v}`);
          proxyReq.setHeader(key, v);
        } else {
          proxyReq.setHeader(key, (value as string) || '');
        }
        // writeToLog(`key: ${key}, val: ${value}`);
      });
    }
    // setting explicity host
    // proxyReq.setHeader('Host', 'booking.com');
    // proxyReq.setHeader('Host', 'localhost:3005');

    // if (req.headers['targetUrl']) {
    //   writeToLog(`>> FOUND targetUrl in request: ${req.headers['targetUrl']}`);
    //   req.headers['targetUrl'] = "https%3A%2F%2Flocalhost%3A3005"
    //   writeToLog(`>> manipulating it to localhost: ${req.headers['targetUrl']}`);
    // }
    // proxyReq.setHeader('targetUrl', req.headers['targetUrl'] || '');
    proxyReq.setHeader('X-Forwarded-Host', proxyReq.getHeader('Host') || '');

    const cookies = (req as any).cookies || {}; // Access parsed cookies

    // Forward AWS WAF token if present
    console.log('Checking for AWS WAF token in headers');
    // if (req.headers['aws-waf-token']) {
    //   console.log('FORWARDING for AWS WAF token in headers');
    //   proxyReq.setHeader('aws-waf-token', req.headers['aws-waf-token']);
    // }
    if (req.headers.cookie) {
      let val = req.headers.cookie;
      val = typeof val === 'string' ? val?.replace('https://booking.com', getPublicHost('basePath')) : '';
      val = typeof val === 'string' ? val?.replace('https://account.booking.com', getPublicHost('basePath')) : '';
      writeToLog(`>> FOUND Cookie in request: ${req.headers.cookie}`);
      // if (cookies['aws-waf-token']) {
      //   console.log('FORWARDING for AWS WAF token in headers', cookies['aws-waf-token']);
      //   proxyReq.setHeader('aws-waf-token', cookies['aws-waf-token']);
      //   // proxyReq.setHeader('X-Forwarded-For', req.headers['x-forwarded-for'] || req.socket.remoteAddress || '');
      //   // proxyReq.setHeader('X-Forwarded-For', '77.29.41.164');
      // }
    }
    // try removing it
    // proxyReq.removeHeader('X-Forwarded-For');
    // proxyReq.setHeader('cookie', '');

    proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36');
    proxyReq.setHeader('X-Forwarded-For', req.headers['x-forwarded-for'] || req.socket.remoteAddress || '');
    proxyReq.setHeader('True-Client-IP', req.headers['x-forwarded-for'] || req.socket.remoteAddress || '');

    if (proxyReq && proxyReq.getHeaders) {
      writeToLog(`>> Final request headers: ${JSON.stringify(proxyReq.getHeaders())}`);
      Object.entries(proxyReq.getHeaders()).forEach(([key, value]) => {
        writeToLog(`key: ${key}, val: ${value}`);
      });
  }

    const body = (req as any).rawBody;
  if (body) {
    writeToLog(`[BODY] for ${req.url}: ${body.toString()}`);
    proxyReq.setHeader('Content-Length', Buffer.byteLength(body));
    proxyReq.write(body); // ✅ Body comes last
    writeToLog(`DIRECT Req url: ${req.url}`);
    writeToLog(`DIRECT POST body: ${body}`);
  } else {
    writeToLog(`NO BODY for ${req.url}`);
  }
};

// export const directReqHandler = (req: IncomingMessage, proxyReq: ProxyRequest) => {

// };

const followRedirectOriginal = (proxyRes: ProxyResponse, req: IncomingMessage, res: ServerResponse<IncomingMessage>) => {
  if (proxyRes.statusCode && proxyRes.statusCode >= 300 && proxyRes.statusCode < 400) {
    const location = proxyRes.headers['location'];

    if (location) {
      try {
        const targetUrl = new URL(location);
        // const proxyBase = `http://localhost:3005/proxy?url=`;
        // const proxyBase = `http://localhost:3005/proxy/`;
        // const proxyBase = `http://localhost:3005/browse/`;
        const proxyBase = getPublicHost();
        const cleanPath = targetUrl.pathname + targetUrl.search; // keep query as-is
        // const proxiedRedirect = `${proxyBase}${encodeURIComponent(targetUrl.href.replace(/\/$/, ''))}`;
        // const proxiedRedirect = `${proxyBase}${targetUrl.href.replace(/\/$/, '')}`;
        const proxiedRedirect = `${proxyBase}${cleanPath}`;

        writeToLog(`>> redirect detected: Target: ${location}, Proxy base: ${proxyBase}, Proxied: ${proxiedRedirect}`);

        console.log(`direct access - redirect intercepted: ${location} -> ${proxiedRedirect}`);

        res.writeHead(proxyRes.statusCode, { Location: proxiedRedirect });
        res.end();
        return;
      } catch (err) {
        console.error('Failed to parse redirect URL:', location, err);
      }
    }
  }
}

const followRedirect = (url: string, res: Response, redirects = 0) => {
  if (redirects >= MAX_REDIRECTS) {
    return res.status(500).send('Too many redirects');
  }

  const target = new URL(url);
  const protocol = target.protocol === 'https:' ? https : http;

  protocol.get(url, (redirectRes: any) => {
    // Pipe the response back to the client
    redirectRes.pipe(res);
    
    // Check for redirects
    if (redirectRes.statusCode >= 300 && redirectRes.statusCode < 400) {
      const newUrl = redirectRes.headers.location;
      followRedirect(newUrl, res, redirects + 1); // Follow the redirect
    }
  }).on('error', (e) => {
    console.error(`Got error: ${e.message}`);
    res.status(500).send('Error occurred during request');
  });
};


export const directResHandler = (proxyRes: ProxyResponse, req: IncomingMessage, res: ServerResponse<IncomingMessage>, originalUrl: string) => {
  
    console.log('Outgoing Proxy (res) Headers:', proxyRes.headers);
    writeToLog(`req url: ${req.url}`);
    writeToLog(`originalUrl: ${originalUrl}`);
    // ORIGINAL that was working but was giving error when AWS challenge was passed
    if (proxyRes.headers.location) {
      console.log('handling redirections');
      const originalLocation = proxyRes.headers.location;
    
      try {
        const originalUrlObj = new URL(originalLocation, getBaseUrl(originalUrl)); // Handles relative redirects
        const currentProxyUrl = new URL(originalUrl, getPublicHost());
    
        if (
          originalUrlObj.hostname === currentProxyUrl.hostname &&
          originalUrlObj.pathname === currentProxyUrl.pathname &&
          originalUrlObj.search === currentProxyUrl.search
        ) {
          writeToLog(`Detected self-redirect to same path: ${originalLocation}. Skipping rewrite.`);
          // Let the browser handle it or block it
          res.writeHead(302, { Location: originalLocation });
          res.end();
          return;
        }
    
        const proxiedLocation = `${getPublicHost('basePath')}${originalUrlObj.pathname}${originalUrlObj.search || ''}`;
    
        writeToLog(`Intercepted redirect: ${originalLocation} → ${proxiedLocation}`);
    
        res.writeHead(proxyRes.statusCode || 302, {
          ...proxyRes.headers,
          'Location': proxiedLocation,
        });
        res.end();
        return;
      } catch (err) {
        console.error('Failed to parse Location header:', proxyRes.headers.location, err);
      }
    }

    // suggested by chatGPT
    // if (proxyRes.headers.location) {
    //   writeToLog('Handling redirection >>>');
    //   try {
    //     const originalLocation = proxyRes.headers.location;
    //     const originalUrlObj = new URL(originalLocation, getBaseUrl(originalUrl)); // Handles relative redirects
    //     const currentProxyUrl = new URL(originalUrl, getPublicHost());
    
    //     if (
    //       originalUrlObj.hostname === currentProxyUrl.hostname &&
    //       originalUrlObj.pathname === currentProxyUrl.pathname &&
    //       originalUrlObj.search === currentProxyUrl.search
    //     ) {
    //       writeToLog(`Detected self-redirect to same path: ${originalLocation}. Skipping rewrite.`);
    //     } else {
    //       const proxiedLocation = `${getPublicHost('basePath')}${originalUrlObj.pathname}${originalUrlObj.search || ''}`;
    //       writeToLog(`Intercepted redirect: ${originalLocation} → ${proxiedLocation}`);
    //       proxyRes.headers.location = proxiedLocation; // ✅ REWRITE HERE
    //     }
    //   } catch (err) {
    //     console.error('Failed to parse Location header:', proxyRes.headers.location, err);
    //   }
    // }

    if (proxyRes.headers['set-cookie']) {
      console.log('Forwarding Set-Cookie:', proxyRes.headers['set-cookie']);
      writeToLog(`>>> FORWARDING Set-Cookie: ${proxyRes.headers['set-cookie']}`);
      // res.setHeader('Set-Cookie', proxyRes.headers['set-cookie']);
      // // res.setHeader('Set-Cookie', proxyRes.headers['set-cookie'].replace(/domain=[^;]+;/, `domain=${targetDomain};`));
      // const setCookies = proxyRes.headers['set-cookie'];
      // if (Array.isArray(setCookies)) {
      //     // Modify each cookie in the array with the specified domain
      //     const modifiedCookies = setCookies.map(cookie => 
      //         cookie.replace(/domain=[^;]+;/, `domain=${getBaseUrl('basePath')};`)
      //     );

      //     // Set the modified cookies as the response header
      //     res.setHeader('Set-Cookie', modifiedCookies);
      //     writeToLog(`>> MODIFYING Set-Cookie: ${modifiedCookies}`);
      // } else if (typeof setCookies === 'string') {
      //     // Handle the case where it's a single cookie string (if applicable)
      //     const modifiedCookie = (setCookies as string).replace(/domain=[^;]+;/, `domain=${getBaseUrl('basePath')};`);
      //     res.setHeader('Set-Cookie', modifiedCookie);
      //     writeToLog(`>> MODIFYING Set-Cookie: ${modifiedCookie}`);
      // }
    }
    

    // moved into a method
    // if (proxyRes.statusCode && proxyRes.statusCode >= 300 && proxyRes.statusCode < 400) {
    //     const location = proxyRes.headers['location'];
    
    //     if (location) {
    //       try {
    //         const targetUrl = new URL(location);
    //         // const proxyBase = `http://localhost:3005/proxy?url=`;
    //         // const proxyBase = `http://localhost:3005/proxy/`;
    //         // const proxyBase = `http://localhost:3005/browse/`;
    //         const proxyBase = getPublicHost();
    //         // const proxiedRedirect = `${proxyBase}${encodeURIComponent(targetUrl.href.replace(/\/$/, ''))}`;
    //         const proxiedRedirect = `${proxyBase}${targetUrl.href.replace(/\/$/, '')}`;

    //         writeToLog(`>> redirect detected: Target: ${location}, Proxy base: ${proxyBase}, Proxied: ${proxiedRedirect}`);
    
    //         console.log(`direct access - redirect intercepted: ${location} -> ${proxiedRedirect}`);
    
    //         res.writeHead(proxyRes.statusCode, { Location: proxiedRedirect });
    //         res.end();
    //         return;
    //       } catch (err) {
    //         console.error('Failed to parse redirect URL:', location, err);
    //       }
    //     }
    //   }
    
      let body: Buffer[] = [];
      delete proxyRes.headers['content-length'];
    
      proxyRes.on('data', (chunk: Buffer) => {
        body.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
      });
    
      proxyRes.on('end', () => {

        // Check for redirect response and follow if necessary
        // if (proxyRes.statusCode && proxyRes.statusCode >= 300 && proxyRes.statusCode < 400) {
        //   const redirectUrl = proxyRes.headers.location; // Get the redirect URL
        //   if (redirectUrl) {
        //     followRedirect(redirectUrl, (res as unknown as Response) ); // Follow the redirect
        //   } 
        // }

        let rawBody = Buffer.concat(body);
        // Log the raw body for debugging
        // console.log('Raw body length:', rawBody.length);
        // console.log('Raw body (first 100 bytes):', rawBody.toString('utf8', 0, Math.min(100, rawBody.length)));
    
        // Handle decompression safely
        try {
          console.log('Raw body length:', rawBody.length);
          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');
          // console.log('WRITING TO FILE', rawBody.length, 'for url', originalUrl);
          const filePath = path.join(__dirname, 'original_response.html');
          const filePathModified = path.join(__dirname, 'modified_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);
        console.log('checking if __NEXT_DATA__ exists in response:');
        if (!rawBody.toString().includes('__NEXT_DATA__')) {
          console.warn("🚨 __NEXT_DATA__ is missing from final response! 🚨");
        } else {
          console.log("✅ __NEXT_DATA__ exists in final response.");
        }
    
        // const baseUrl = 'http://localhost:3005/proxy/'; // replace wtih env vars for different envs
        // const oU = originalUrl || 'https://www.bosch-diy.com';
        // if (originalUrl) {
        //   const baseOriginalUrl = getBaseUrl(originalUrl);
        //   const rewrittenUrl = originalUrl ? `${baseUrl}${baseOriginalUrl}` : '';
        //   // Add a <base> tag to ensure relative URLs resolve correctly
        //   response = response.replace(/<head>/, `<head><base href="${rewrittenUrl}">`);
  
  
        //   // Rewrite only relative URLs to absolute URLs
        //   response = response.replace(/(href|src)="\/([^"]+)"/g, `$1="${rewrittenUrl}/$2"`);
        // }
  
        // const originalHost = new URL(originalUrl || '').host;
        // const baseProxyUrl = `http://localhost:3005/proxy?url=`;
        // // 🔹 Skip URLs pointing to static assets (JS, CSS, images, fonts)
        // const staticFileExtensions = /\.(js|css|png|jpe?g|gif|svg|woff2?|ttf|eot|ico|mp4|webm|ogg|json|xml)(\?.*)?$/i;
  
  
        // // 🔹 Rewrite <a href="..."> links to go through the proxy
        // console.log('Rewriting absolute <a href="..."> links');
        // response = response.replace(
        //   /<a\s+[^>]*?href=["'](https?:\/\/([^"']+))["']/gi,
        //   (match, fullUrl, domain) => {
        //     if (domain.includes(originalHost) && !staticFileExtensions.test(fullUrl)) {
        //       return match.replace(fullUrl, `${baseProxyUrl}${encodeURIComponent(fullUrl)}`);
        //     }
        //     return match;
        //   }
        // );
  
        // // 🔹 Rewrite relative <a href="..."> links (e.g., /page.html) to absolute via the proxy
        // console.log('Rewriting relative <a href="..."> links');
        // response = response.replace(
        //   /<a\s+[^>]*?href=["'](\/[^"']*)["']/gi,
        //   (match, relativePath) => {
        //     if (!staticFileExtensions.test(relativePath)) {
        //       return match.replace(relativePath, `${baseProxyUrl}${encodeURIComponent(originalUrl + relativePath)}`);
        //     }
        //     return match;
        //   }
        // );
    
        // // 🔹 Rewrite <form action="..."> to go through the proxy
        // console.log('Rewriting forms <form action="..."> links');
        // response = response.replace(
        //   /<form\s+[^>]*?action=["'](https?:\/\/([^"']+))["']/gi,
        //   (match, fullUrl, domain) => {
        //     if (domain.includes(originalHost) && !staticFileExtensions.test(fullUrl)) {
        //       return match.replace(fullUrl, `${baseProxyUrl}${encodeURIComponent(fullUrl)}`);
        //     }
        //     return match;
        //   }
        // );
  
        // // 🔹 Rewrite relative <form action="..."> paths
        // response = response.replace(
        //   /<form\s+[^>]*?action=["'](\/[^"']*)["']/gi,
        //   (match, relativePath) => {
        //     return match.replace(relativePath, `${baseProxyUrl}${encodeURIComponent(originalUrl + relativePath)}`);
        //   }
        // );
  
        if (!originalUrl.includes('js_tracking') && !originalUrl.includes('favicon.ico')) {
          fs.writeFile(filePath, response, (err) => {
            if (err) {
                console.error('Error writing to file', err);
              }
            console.error('Successtully writing response to file', err);
          });
        }

        console.log('!!!! Rewriting  links');
        response = directSimpleRewriteLinks(response, originalUrl);
        console.log('!!!! writing to file', filePathModified);
  
        if (!originalUrl.includes('js_tracking') && !originalUrl.includes('favicon.ico')) {
          fs.writeFile(filePathModified, response, (err) => {
            if (err) {
                console.error('Error writing to file', err);
              }
            console.error('Successtully writing response to file', err);
          });
        }
    
          // force all internal navigation to go trough the proxy
          const overrideScript = `
            <script>
              (function() {
                const originalPushState = window.history.pushState;
                const originalReplaceState = window.history.replaceState;
    
                function sanitizeUrl(url) {
                  if (!url.startsWith('/') && !url.startsWith(window.location.origin)) {
                    console.warn('🔍 Blocking navigation to external URL:', url);
                    return window.location.pathname; // Stay on the same page
                  }
                  return url;
                }
    
                window.history.pushState = function(state, title, url) {
                  return originalPushState.call(this, state, title, sanitizeUrl(url));
                };
    
                window.history.replaceState = function(state, title, url) {
                  return originalReplaceState.call(this, state, title, sanitizeUrl(url));
                };
              })();
            </script>`;
    
          const overrideScriptToSolvePushState_orig = `
            <script>
              (function() {
                function sanitizeUrl(url) {
                  // If the URL is trying to go to another origin, block it
                  if (!url.startsWith(window.location.origin)) {
                    console.warn('🚫 Blocking cross-origin replaceState:', url);
                    return window.location.pathname; // Stay on the same page
                  }
                  return url;
                }
    
                function overrideHistoryMethod(method) {
                  const original = history[method];
    
                  Object.defineProperty(history, method, {
                    configurable: false,
                    enumerable: false,
                    writable: false,
                    value: function(state, title, url) {
                      const safeUrl = sanitizeUrl(url);
                      try {
                        return original.call(this, state, title, safeUrl);
                      } catch (e) {
                        console.error(\`❌ History. error prevented:\`, e);
                      }
                    }
                  });
                }
    
                overrideHistoryMethod('replaceState');
                overrideHistoryMethod('pushState');
    
                console.log('✅ History override (Object.defineProperty) injected');
              })();
            </script>`;
    
          const overrideScriptToSolvePushState = `
            <script>
      (function() {
        console.log('✅ Injecting domain and history overrides...');
    
        // Override history.replaceState to prevent cross-origin errors
        const originalReplaceState = window.history.replaceState;
        window.history.replaceState = function(state, title, url) {
          try {
            if (url && url.startsWith("https://www.bosch-diy.com")) {
              console.warn("🚨 Prevented replaceState to", url);
              return;
            }
            originalReplaceState.apply(this, arguments);
            console.log("✅ replaceState called with:", state, title, url);
          } catch (e) {
            console.error("❌ Error in replaceState override:", e);
          }
        };
    
        console.log("✅ history.replaceState overridden successfully");
      })();
            </script>`;
    
          const fixDomainScript = `
            <script>
              console.log('✅ Injecting document.domain fix...');
    
              try {
                document.domain = "localhost";
                console.log("✅ document.domain set to localhost");
              } catch (e) {
                console.warn("❌ Unable to set document.domain:", e);
              }
            </script>`;
    
          console.log("🔹 Adding override script to response");
          // response = response.replace('</head>', `${overrideScriptToSolvePushState}${fixDomainScript}${overrideScript}</head>`);
    
    
          rawBody = Buffer.from(response, 'utf8');
    
          const encoding = proxyRes.headers['content-encoding'] || '';
          console.log("🔄 Encoding Type:", encoding);
    
          if (encoding.includes('gzip')) {
            rawBody = zlib.gunzipSync(rawBody);
          } else if (encoding.includes('br')) {
            rawBody = zlib.brotliDecompressSync(rawBody);
          } else if (encoding.includes('deflate')) {
            rawBody = zlib.inflateSync(rawBody);
          }
    
          delete proxyRes.headers['content-encoding']; // Remove encoding header
          if (proxyRes.headers['set-cookie']) {
            writeToLog(`set-cookie found: ${proxyRes.headers['set-cookie']}`);
            proxyRes.headers['set-cookie'] = proxyRes.headers['set-cookie'].map((cookie: string) =>
              cookie.replace(/Domain=\.?bosch-diy\.com/gi, 'Domain=localhost').replace(/Secure;/gi, '') // Remove Secure for local dev
            );
          }
          if (proxyRes.headers['content-security-policy']) {
            delete proxyRes.headers['content-security-policy']; // Remove CSP
          }
          if (proxyRes.headers['content-security-policy-report-only']) {
            delete proxyRes.headers['content-security-policy-report-only']; // Remove CSP report-only mode
          }
        }
    
        const filePathModified = path.join(__dirname, 'modified_response.html');
        if (!originalUrl.includes('js_tracking')) {
          fs.writeFile(filePathModified, rawBody, (err) => {
            if (err) {
                console.error('Error writing to file', err);
              }
            console.error('Successtully writing response to file', err);
          });
        }

        // 🔹 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.setHeader('Set-Cookie', 'headers');

        writeToLog(`response headers: ${JSON.stringify(proxyRes.headers)}`);
    
        res.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
        res.end(rawBody);
      });

}

export const directResHandler_boilerPlate = (proxyRes: ProxyResponse, req: IncomingMessage, res: ServerResponse<IncomingMessage>, originalUrl: string) => {
  
    let body: Buffer[] = [];
    delete proxyRes.headers['content-length'];
  
    proxyRes.on('data', (chunk: Buffer) => {
      body.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
    });
  
    proxyRes.on('end', () => {

      let rawBody = Buffer.concat(body);
      
      res.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
      res.end(rawBody);
    });

}