-- Minimal test configuration with Tree-sitter support (debug version)
-- Run with: nvim -u minimal-nvim-treesitter-debug.lua example.eas

-- Enable syntax highlighting (fallback)
vim.cmd('syntax enable')

-- Set up the runtime path
vim.opt.runtimepath:prepend(vim.fn.stdpath('data') .. '/site/pack/packer/start/nvim-treesitter')
vim.opt.runtimepath:prepend(vim.fn.stdpath('data') .. '/site/pack/packer/start/nvim-lspconfig')

-- Add the tree-sitter grammar path to runtime
vim.opt.runtimepath:append(vim.fn.expand('~/projects/evm-asm-lsp/crates/tree-sitter-evm-asm'))

-- Simple filetype detection
vim.api.nvim_create_autocmd({"BufRead", "BufNewFile"}, {
  pattern = {"*.eas", "*.evm", "*.evmasm"},
  callback = function()
    vim.bo.filetype = "evmasm"
    -- Force syntax sync
    vim.cmd('syntax sync fromstart')
  end,
})

-- Check if treesitter is available
local ok_ts, ts = pcall(require, 'nvim-treesitter.configs')
if ok_ts then
  -- Add our custom parser configuration
  local parser_config = require "nvim-treesitter.parsers".get_parser_configs()
  parser_config.evm_asm = {
    install_info = {
      -- Point to the tree-sitter grammar directory
      url = vim.fn.expand("~/projects/evm-asm-lsp/crates/tree-sitter-evm-asm"),
      files = {"src/parser.c"},
      branch = "main",
      generate_requires_npm = false,
      requires_generate_from_grammar = false,
    },
    filetype = "evmasm",
  }

  -- Configure Tree-sitter with explicit settings
  ts.setup {
    ensure_installed = {},  -- Don't auto-install
    sync_install = false,
    highlight = {
      enable = true,
      disable = {},
      additional_vim_regex_highlighting = false,
    },
    indent = {
      enable = true,
    },
  }
  
  -- Manually add queries path
  local queries_path = vim.fn.expand("~/projects/evm-asm-lsp/crates/tree-sitter-evm-asm/queries")
  vim.opt.runtimepath:append(queries_path)
  
  -- Enable Tree-sitter based folding
  vim.opt.foldmethod = "expr"
  vim.opt.foldexpr = "nvim_treesitter#foldexpr()"
  vim.opt.foldenable = false -- Don't fold by default
  
  -- Force highlighting for evmasm files
  vim.api.nvim_create_autocmd("FileType", {
    pattern = "evmasm",
    callback = function()
      -- Try to enable highlighting explicitly
      vim.defer_fn(function()
        local ok, err = pcall(vim.cmd, 'TSBufEnable highlight')
        if not ok then
          print("Failed to enable TS highlighting:", err)
        end
      end, 100)
    end,
  })
  
  print("Tree-sitter configured! Run :TSInstall evm_asm if not already installed")
else
  print("nvim-treesitter not found. Install with:")
  print("git clone https://github.com/nvim-treesitter/nvim-treesitter ~/.local/share/nvim/site/pack/packer/start/nvim-treesitter")
end

-- LSP configuration (same as before)
local ok_lsp, lspconfig = pcall(require, 'lspconfig')
if ok_lsp then
  local configs = require('lspconfig.configs')
  
  configs.evm_asm_lsp = {
    default_config = {
      cmd = { vim.fn.expand('~/projects/evm-asm-lsp/target/release/evm-asm-lsp') },
      filetypes = { 'evmasm' },
      root_dir = function() return vim.fn.getcwd() end,
    },
  }
  
  lspconfig.evm_asm_lsp.setup{
    on_attach = function(_, bufnr)
      print("EVM ASM LSP attached!")
      vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = bufnr })
      vim.keymap.set('n', 'gd', vim.lsp.buf.definition, { buffer = bufnr })
      vim.keymap.set('n', 'gr', vim.lsp.buf.references, { buffer = bufnr })
    end,
  }
end

-- Debug commands
vim.api.nvim_create_user_command('TSDebug', function()
  print("=== Tree-sitter Debug Info ===")
  print("Filetype:", vim.bo.filetype)
  local has_parser = require("nvim-treesitter.parsers").has_parser("evm_asm")
  print("Parser installed:", has_parser)
  if has_parser then
    local parser_ok, parser = pcall(vim.treesitter.get_parser, 0, "evm_asm")
    print("Parser works:", parser_ok)
  end
  print("Queries path exists:", vim.fn.isdirectory(vim.fn.expand("~/projects/evm-asm-lsp/crates/tree-sitter-evm-asm/queries")) == 1)
end, {})

print([[
Minimal EVM ASM config with Tree-sitter loaded (debug mode)!

Commands:
1. :TSInstall evm_asm    - Install the parser
2. :TSDebug              - Show debug info
3. :TSBufEnable highlight - Force enable highlighting

After installing, restart nvim and highlighting should work.
]])