import { d as defineEventHandler, r as readBody, c as createError, u as useRuntimeConfig, s as setResponseHeaders, a as sendStream } from '../../../nitro/nitro.mjs';
import 'node:http';
import 'node:https';
import 'node:crypto';
import 'stream';
import 'events';
import 'http';
import 'crypto';
import 'buffer';
import 'zlib';
import 'https';
import 'net';
import 'tls';
import 'url';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'vue-router';
import '@prisma/client';
import '@prisma/adapter-better-sqlite3';
import 'fs';
import 'path';
import 'fs/promises';
import 'child_process';
import 'node:child_process';
import 'node:url';

const autocreate_post = defineEventHandler(async (event) => {
  var _a;
  const body = await readBody(event);
  if (!((_a = body.prompt) == null ? void 0 : _a.trim())) {
    throw createError({
      statusCode: 400,
      message: "Prompt is required"
    });
  }
  const config = useRuntimeConfig();
  if (!config.anthropicApiKey) {
    throw createError({
      statusCode: 503,
      message: "Claude API not configured"
    });
  }
  setResponseHeaders(event, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive"
  });
  const encoder = new TextEncoder();
  const stream = new ReadableStream({
    async start(controller) {
      var _a2, _b;
      try {
        const response = await fetch("https://api.anthropic.com/v1/messages", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "x-api-key": config.anthropicApiKey,
            "anthropic-version": "2023-06-01"
          },
          body: JSON.stringify({
            model: config.anthropicModel || "claude-3-5-sonnet-20241022",
            max_tokens: 4096,
            stream: true,
            system: `You are an assistant that generates pipeline column configurations for AutoCode.
When given a description, suggest appropriate columns with names, descriptions, and types.
Think through the problem step by step, then return your suggestions as a JSON array at the end.
Each suggestion should have: name, description, type (generic, review, testing, deployment, etc.), and config object.`,
            messages: [
              {
                role: "user",
                content: body.prompt
              }
            ]
          })
        });
        if (!response.ok) {
          controller.enqueue(
            encoder.encode(
              `data: ${JSON.stringify({ type: "error", message: "Claude API error" })}

`
            )
          );
          controller.close();
          return;
        }
        const reader = (_a2 = response.body) == null ? void 0 : _a2.getReader();
        let thinkingBuffer = "";
        if (reader) {
          const streamDecoder = new TextDecoder();
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            const chunk = streamDecoder.decode(value, { stream: true });
            const lines = chunk.split("\n");
            for (const line of lines) {
              if (line.startsWith("data: ")) {
                try {
                  const data = JSON.parse(line.slice(6));
                  if (data.type === "content_block_delta") {
                    const text = ((_b = data.delta) == null ? void 0 : _b.text) || "";
                    thinkingBuffer += text;
                    controller.enqueue(
                      encoder.encode(
                        `data: ${JSON.stringify({ type: "thinking", content: text })}

`
                      )
                    );
                  }
                } catch {
                }
              }
            }
          }
        }
        const proposals = parseProposals(thinkingBuffer);
        controller.enqueue(
          encoder.encode(`data: ${JSON.stringify({ type: "proposals", proposals })}

`)
        );
        controller.close();
      } catch {
        controller.enqueue(
          encoder.encode(
            `data: ${JSON.stringify({ type: "error", message: "Generation failed" })}

`
          )
        );
        controller.close();
      }
    }
  });
  return sendStream(event, stream);
});
function parseProposals(content) {
  const jsonMatch = content.match(/\[[\s\S]*\]/);
  if (jsonMatch) {
    try {
      const parsed = JSON.parse(jsonMatch[0]);
      return parsed.map((item) => ({
        name: item.name || "Unnamed",
        description: item.description || "",
        type: item.type || "generic",
        config: item.config || {}
      }));
    } catch {
    }
  }
  return [];
}

export { autocreate_post as default };
//# sourceMappingURL=autocreate.post.mjs.map
