// @ts-check
"use strict";

const path = require("node:path");
const vscode = require("vscode");
const { LanguageClient, TransportKind } = require("vscode-languageclient/node");

const WRN_LANGUAGE_ID = "wrn";
/** @type {LanguageClient | undefined} */
let client;

/** @param {vscode.TextDocument} document */
async function recoverWrnLanguage(document) {
  if (!document.fileName.toLowerCase().endsWith(".wrn")) return;
  if (!["plaintext", "wire"].includes(document.languageId)) return;
  try {
    await vscode.languages.setTextDocumentLanguage(document, WRN_LANGUAGE_ID);
  } catch (error) {
    console.warn(
      "[wrnexus] unable to recover .wrn language association:",
      error instanceof Error ? error.message : String(error),
    );
  }
}

/** @param {vscode.ExtensionContext} context */
async function activate(context) {
  for (const document of vscode.workspace.textDocuments) void recoverWrnLanguage(document);
  context.subscriptions.push(
    vscode.workspace.onDidOpenTextDocument((document) => void recoverWrnLanguage(document)),
  );

  if (!vscode.workspace.getConfiguration("wrnexus").get("languageServer.enable", true)) return;

  const module = path.join(context.extensionPath, "src", "language-server.cjs");
  client = new LanguageClient(
    "wrnexusLanguageServer",
    "WRNexus Language Server",
    {
      run: { module, transport: TransportKind.stdio },
      debug: { module, transport: TransportKind.stdio, options: { execArgv: ["--nolazy"] } },
    },
    { documentSelector: [{ scheme: "file", language: WRN_LANGUAGE_ID }] },
  );
  await client.start();
}

async function deactivate() {
  const running = client;
  client = undefined;
  if (running) await running.stop();
}

module.exports = { activate, deactivate, recoverWrnLanguage };
