// Lightweight Vite plugin that injects a small client-side script to
// forward selected console messages to the dev server. The dev server
// registers an endpoint at /__console_forward and will log the messages
// so you can see browser console output from the container logs.

export function consoleForwardPlugin(opts = {}) {
  const levels = Array.isArray(opts.levels) && opts.levels.length ? opts.levels : ["log", "warn", "error"];
  const enabled = opts.enabled !== false; // Default to true

  if (!enabled) {
    // No-op plugin
    return {
      name: "vite-console-forward-plugin",
      enforce: "pre",
      transformIndexHtml(html) {
        return html;
      },
    };
  }
  return {
    name: "vite-console-forward-plugin",
    enforce: "pre",

    configureServer(server) {
      // Register a simple POST handler to receive the forwarded console
      // messages from the browser. We keep it minimal and robust.
      server.middlewares.use("/__console_forward", (req, res, next) => {
        if (req.method !== "POST") return next();

        let body = "";
        req.on("data", (chunk) => (body += chunk));
        req.on("end", () => {
          try {
            const payload = JSON.parse(body || "{}");
            const lvl = payload.level || "log";
            const args = Array.isArray(payload.args) ? payload.args : payload.args ? [payload.args] : [];
            const stack = payload.stack;

            // Print an informative prefix so these lines are easy to grep in container logs
            if (stack) {
              console.error("[frontend][error]", stack);
            }

            // Use the requested console level where available; fall back to console.log
            const fn = console[lvl] || console.log;
            try {
              fn("[frontend]", ...args);
            } catch (e) {
              // Ensure we don't crash the dev server due to malformed payloads
              console.log("[frontend][fallback]", ...args);
            }
          } catch (e) {
            console.error("console-forward: failed to parse payload", e);
          }
          res.statusCode = 204;
          res.end();
        });
      });
    },

    transformIndexHtml(html) {
      // Only inject the forwarding script in non-production mode. Vite sets
      // NODE_ENV during the dev server; keep this conservative.
      if (process.env.NODE_ENV === "production") return html;

      const script = `(function(){
  if (window.__vite_console_forward_installed__) return;
  window.__vite_console_forward_installed__ = true;

  function safeSerialize(v){
    try { return typeof v === 'string' ? v : JSON.stringify(v); }
    catch(e){ try{ return String(v); }catch(_){ return 'unserializable'; } }
  }

var levels = ${JSON.stringify(levels)};
levels.forEach(function(l){
  var orig = console[l];
  if (!orig) return;
  
  console[l] = function(){
    // Call original first
    try{ orig.apply(console, arguments); }catch(e){/* ignore */}
    
    // Capture the real caller from the stack
    try{
      var stack = new Error().stack;
      var callerLine = null;
      
      // Parse stack to find the first line that's NOT this wrapper
      if (stack) {
        var lines = stack.split('\\n');
        // Skip the first 2-3 lines (Error, this wrapper)
        for (var i = 2; i < lines.length; i++) {
          if (lines[i] && !lines[i].includes('vite-console-forward')) {
            callerLine = lines[i].trim();
            break;
          }
        }
      }
      
      var args = Array.prototype.slice.call(arguments).map(safeSerialize);
      var payload = JSON.stringify({ 
        level: l, 
        args: args,
        caller: callerLine  // Include the real caller
      });
      
      if (navigator.sendBeacon) {
        try { navigator.sendBeacon('/__console_forward', payload); return; } catch(e){}
      }
      fetch('/__console_forward', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload }).catch(function(){/* ignore */});
    }catch(e){/* ignore */}
  };
});

  window.addEventListener('error', function(ev){
    try{
      var stack = ev && ev.error && ev.error.stack ? ev.error.stack : (ev.message + ' at ' + ev.filename + ':' + ev.lineno + ':' + ev.colno);
      var payload = JSON.stringify({ level: 'error', stack: stack });
      if (navigator.sendBeacon) { try { navigator.sendBeacon('/__console_forward', payload); return; } catch(e){} }
      fetch('/__console_forward', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload }).catch(function(){});
    }catch(e){}
  }, true);
})();`;

      return html.replace(/<\/head>/i, `<script>${script}</script></head>`);
    },
  };
}

export default consoleForwardPlugin;
