import * as path from 'path'
import * as vscode from 'vscode'
import * as fs from 'fs'
import {LanguageClient, LanguageClientOptions, ServerOptions, TransportKind} from 'vscode-languageclient/node'

let client: LanguageClient

function findSystemTslServer(): string | null {
  const binary = process.platform === 'win32' ? 'tsl-server.exe' : 'tsl-server'
  const pathDirs = process.env.PATH?.split(path.delimiter) || []

  for (const dir of pathDirs) {
    const fullPath = path.join(dir, binary)
    if (fs.existsSync(fullPath)) {
      return fullPath
    }
  }

  return null
}

export function activate(context: vscode.ExtensionContext) {
  const bundledPath = context.asAbsolutePath(
    path.join('bin', process.platform === 'win32' ? 'tsl-server.exe' : 'tsl-server')
  )

  // 查找路径优先级：插件目录 -> 系统 PATH
  let serverExe: string | null = null
  if (fs.existsSync(bundledPath)) {
    serverExe = bundledPath
  } else {
    serverExe = findSystemTslServer()
  }

  if (!serverExe) {
    vscode.window.showErrorMessage(
      "Cannot find tsl-server. Please install it globally or include it in your extension's server directory."
    )
    return
  }

  const serverOptions: ServerOptions = {
    run: {command: serverExe, transport: TransportKind.stdio, args: ['--log=trace', '--log-stderr']},
    debug: {command: serverExe, transport: TransportKind.stdio}
  }

  const clientOptions: LanguageClientOptions = {
    documentSelector: [{scheme: 'file', language: 'tsl'}],
    synchronize: {
      fileEvents: vscode.workspace.createFileSystemWatcher('**/*.tsl')
    }
  }

  client = new LanguageClient(
    'tslLanguageServer', // 客户端唯一ID
    'TSL Language Server', // 用户可见名称
    serverOptions,
    clientOptions
  )

  client.start()
}

export function deactivate(): Thenable<void> | undefined {
  return client ? client.stop() : undefined
}
