const fs = require("fs");
const path = require("path");
const { err, createResponseDumper } = require("../logger");
const { IS_DEV } = require("../config");
const { fetchRouter, pipeSSE } = require("./base");
const { DATA_DIR } = require("../paths");

function getAntigravityDirectConfig() {
  const dbPath = path.join(DATA_DIR, "db.json");
  try {
    if (fs.existsSync(dbPath)) {
      const db = JSON.parse(fs.readFileSync(dbPath, "utf8"));
      return {
        enabled: db.antigravityDirect === true,
        endpoint: db.antigravityEndpoint || "http://localhost:20128/v1internal/antigravity:streamGenerateContent"
      };
    }
  } catch (e) {}
  return { enabled: false, endpoint: "http://localhost:20128/v1internal/antigravity:streamGenerateContent" };
}

/**
 * Intercept Antigravity request — forward Gemini body either to /v1/chat/completions
 * or verbatim via AG-Direct mode.
 */
async function intercept(req, res, bodyBuffer, mappedModel) {
  const dumper = IS_DEV ? createResponseDumper(req, "intercept-antigravity") : null;
  const isStream = req.url.includes(":streamGenerateContent");
  const directConfig = getAntigravityDirectConfig();

  try {
    if (directConfig.enabled) {
      // AG-Direct Mode: forward verbatim to internal stream endpoint
      // Strip content-length to let fetch re-calculate it (prevents framing errors)
      const fwdHeaders = { ...req.headers };
      delete fwdHeaders["content-length"];
      
      const fetchRes = await fetch(directConfig.endpoint, {
        method: "POST",
        headers: fwdHeaders,
        body: bodyBuffer
      });
      await pipeSSE(fetchRes, res, dumper);
      return;
    }

    // Standard Mode: forward Gemini body to /v1/chat/completions
    // Router auto-detects format via body.userAgent==="antigravity" + body.request.contents
    const body = JSON.parse(bodyBuffer.toString());
    if (body.model) body.model = mappedModel;

    const routerRes = await fetchRouter(body, "/v1/chat/completions", req.headers);
    await pipeSSE(routerRes, res, dumper);
  } catch (error) {
    err(`[antigravity] ${error.message}`);
    if (dumper) { dumper.writeChunk(`\n[ERROR] ${error.message}\n`); dumper.end(); }
    // For stream endpoint, send SSE error chunk so SDK doesn't hang waiting
    if (isStream) {
      if (!res.headersSent) res.writeHead(200, { "Content-Type": "text/event-stream" });
      res.end(`data: ${JSON.stringify({ error: { message: error.message } })}\r\n\r\n`);
    } else {
      if (!res.headersSent) res.writeHead(500, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: { message: error.message, type: "mitm_error" } }));
    }
  }
}

module.exports = { intercept };
