import { loadEnv } from 'vite';

// src/vite.ts

// src/worker.ts
var COPILOT_SYSTEM_PROMPT = `You are an advanced AI writing assistant, similar to VSCode Copilot but for general text. Your task is to predict and generate the next part of the text based on the given context.

Rules:
- Continue the text naturally up to the next punctuation mark (., ,, ;, :, ?, or !).
- Maintain style and tone. Don't repeat given text.
- For unclear context, provide the most likely continuation.
- Handle code snippets, lists, or structured text if needed.
- Don't include """ in your response.
- CRITICAL: Always end with a punctuation mark.
- CRITICAL: Avoid starting a new block. Do not use block formatting like >, #, 1., 2., -, etc. The suggestion should continue in the same block as the context.
- If no context is provided or you can't generate a continuation, return "0" without explanation.`;
function getApiBaseUrl(env) {
  return env.VITE_DOCYRUS_API_URL;
}
function getAgentId(env) {
  return env.VITE_DOCYRUS_EDITOR_AGENT_ID || env.VITE_DOCYRUS_AGENT_ID;
}
function getAuthToken(request) {
  const authHeader = request.headers.get("authorization");
  return authHeader?.replace("Bearer ", "") || void 0;
}
async function handleAiCommand(request, env) {
  if (request.method !== "POST") {
    return new Response(JSON.stringify({ error: "Method not allowed" }), {
      status: 405,
      headers: { "Content-Type": "application/json" }
    });
  }
  try {
    const body = await request.json();
    const token = getAuthToken(request);
    if (!token) {
      return new Response(
        JSON.stringify({ error: "Unauthorized", message: "No authentication token found. Please log in." }),
        { status: 401, headers: { "Content-Type": "application/json" } }
      );
    }
    const apiBaseUrl = getApiBaseUrl(env);
    if (!apiBaseUrl) {
      return new Response(
        JSON.stringify({ error: "VITE_DOCYRUS_API_URL is not configured" }),
        { status: 500, headers: { "Content-Type": "application/json" } }
      );
    }
    const agentId = getAgentId(env);
    if (!agentId) {
      return new Response(
        JSON.stringify({ error: "VITE_DOCYRUS_AGENT_ID is not configured" }),
        { status: 500, headers: { "Content-Type": "application/json" } }
      );
    }
    const { messages, ctx } = body;
    let editorContext;
    if (ctx) {
      const contextData = { toolName: ctx.toolName };
      if (ctx.selection) contextData.selection = ctx.selection;
      if (ctx.children) contextData.children = ctx.children;
      editorContext = JSON.stringify(contextData);
    }
    const response = await fetch(`${apiBaseUrl}/v1/ai/agents/${agentId}/chat`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify({
        agentId,
        messages: messages ?? [],
        mode: "agent",
        stream: true,
        additionalContext: editorContext
      })
    });
    if (!response.ok) {
      const errorText = await response.text();
      return new Response(
        errorText || JSON.stringify({ error: "Backend API error" }),
        { status: response.status, headers: { "Content-Type": "application/json" } }
      );
    }
    return new Response(response.body, {
      headers: {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive"
      }
    });
  } catch (error) {
    console.error("[AI Command] Error:", error);
    return new Response(
      JSON.stringify({ error: "Internal server error", message: error instanceof Error ? error.message : "Unknown error" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
}
async function handleAiCopilot(request, env) {
  if (request.method !== "POST") {
    return new Response(JSON.stringify({ error: "Method not allowed" }), {
      status: 405,
      headers: { "Content-Type": "application/json" }
    });
  }
  try {
    const body = await request.json();
    const token = getAuthToken(request);
    if (!token) {
      return new Response(
        JSON.stringify({ error: "Unauthorized" }),
        { status: 401, headers: { "Content-Type": "application/json" } }
      );
    }
    const apiBaseUrl = getApiBaseUrl(env);
    if (!apiBaseUrl) {
      return new Response(
        JSON.stringify({ error: "VITE_DOCYRUS_API_URL is not configured" }),
        { status: 500, headers: { "Content-Type": "application/json" } }
      );
    }
    const agentId = getAgentId(env);
    if (!agentId) {
      return new Response(
        JSON.stringify({ error: "VITE_DOCYRUS_AGENT_ID is not configured" }),
        { status: 500, headers: { "Content-Type": "application/json" } }
      );
    }
    const response = await fetch(`${apiBaseUrl}/v1/ai/agents/${agentId}/chat`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify({
        agentId,
        messages: [{ role: "system", content: COPILOT_SYSTEM_PROMPT }, { role: "user", content: body.prompt }],
        mode: "agent",
        stream: true
      })
    });
    if (!response.ok) {
      const errorText = await response.text();
      return new Response(
        errorText || JSON.stringify({ error: "Backend API error" }),
        { status: response.status, headers: { "Content-Type": "application/json" } }
      );
    }
    return new Response(response.body, {
      headers: {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive"
      }
    });
  } catch (error) {
    console.error("[AI Copilot] Error:", error);
    return new Response(
      JSON.stringify({ error: "Internal server error", message: error instanceof Error ? error.message : "Unknown error" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
}

// src/vite.ts
function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on("data", (chunk) => chunks.push(chunk));
    req.on("end", () => resolve(Buffer.concat(chunks)));
    req.on("error", reject);
  });
}
function plateEditorPlugin() {
  let env;
  return {
    name: "plate-editor-ai",
    configResolved(config) {
      env = loadEnv(config.mode, config.root, "");
    },
    configureServer(server) {
      server.middlewares.use(async (req, res, next) => {
        if (req.url !== "/api/ai/command" && req.url !== "/api/ai/copilot") {
          return next();
        }
        const body = await readBody(req);
        const request = new Request(`http://localhost${req.url}`, {
          method: req.method,
          headers: req.headers,
          body: body.length > 0 ? new Uint8Array(body) : void 0
        });
        const response = req.url === "/api/ai/command" ? await handleAiCommand(request, env) : await handleAiCopilot(request, env);
        res.statusCode = response.status;
        response.headers.forEach((value, key) => res.setHeader(key, value));
        if (response.body) {
          const reader = response.body.getReader();
          const pump = async () => {
            const { done, value } = await reader.read();
            if (done) {
              res.end();
              return;
            }
            res.write(value);
            await pump();
          };
          await pump();
        } else {
          res.end();
        }
      });
    }
  };
}

export { plateEditorPlugin };
//# sourceMappingURL=vite.js.map
//# sourceMappingURL=vite.js.map