import * as vscode from "vscode";
import axios from "axios";

export function activate(context: vscode.ExtensionContext) {
  let disposable = vscode.commands.registerCommand(
    "extension.processAndInsert",
    async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) {
        vscode.window.showErrorMessage("No active editor!");
        return;
      }

      const document = editor.document;
      const content = document.getText();

      try {
        vscode.window.showInformationMessage(
          "Streaming response from the model…",
        );
        await streamApiCall(content, editor);
        vscode.window.showInformationMessage("Summary successfully generated!");
      } catch (error) {
        if (error instanceof Error) {
          vscode.window.showErrorMessage(
            "Error processing API request: " + error.message,
          );
        } else {
          vscode.window.showErrorMessage("An unknown error occurred");
        }
      }
    },
  );

  context.subscriptions.push(disposable);
}

async function streamApiCall(
  content: string,
  editor: vscode.TextEditor,
): Promise<void> {
  const config = vscode.workspace.getConfiguration("Drop Summary");
  const apiUrl =
    config.get<string>("apiUrl") || "http://127.0.0.1:11434/api/generate";
  const model = config.get<string>("model") || "drop-summary";

  const response = await axios.post(
    apiUrl,
    {
      model: model,
      stream: true,
      keep_alive: "10m",
      prompt: content,
    },
    {
      responseType: "stream",
    },
  );

  let intro =
    "_(This is an AI-generated summary of today's Drop using Ollama + llama 3.2 and a custom prompt.)_";
  let position = editor.selection.active;

  await editor.edit((editBuilder) => {
    editBuilder.insert(position, intro + "\n\n");
    position = position.translate(2, 2);
  });

  for await (const chunk of response.data) {
    const chunkStr = chunk.toString();
    try {
      const parsed = JSON.parse(chunkStr);
      if (parsed.response) {
        let responseText = parsed.response;

        // Replace escaped newlines with actual newlines
        responseText = responseText.replace(/\\n/g, "\n");

        await editor.edit((editBuilder) => {
          editBuilder.insert(position, responseText);
          const lines = responseText.split("\n");
          const lastLineLength = lines[lines.length - 1].length;
          position = position.translate(lines.length - 1, lastLineLength);
        });
      }
    } catch (e) {
      console.error("Error parsing JSON:", e);
    }
  }
}

export function deactivate() {}
