---@brief
---
--- EXPERIMENTAL: This API is unstable, do not use it. Its semantics are not yet finalized.
--- Subscribe to this issue to stay updated: https://github.com/neovim/neovim/issues/25509
---
--- Provides operations to compare, calculate, and convert ranges represented by |vim.Range|
--- objects.

local validate = vim.validate
local api = vim.api

--- Represents a range. Call `vim.range()` to create a new range.
---
--- A range contains a start and end position (see |vim.Pos|). The end position is exclusive.
--- Positions must have the same optional fields.
---
--- May include optional fields that enable additional capabilities, such as format conversions.
---
--- Example:
--- ```lua
--- local pos1 = vim.pos(0, 3, 5)
--- local pos2 = vim.pos(0, 4, 0)
---
--- -- Create a range from two positions.
--- local range1 = vim.range(pos1, pos2)
--- -- Or create a range from four integers representing start and end positions.
--- local range2 = vim.range(0, 3, 5, 4, 0)
---
--- -- Because `vim.Range` is end exclusive, `range1` and `range2` both represent
--- -- a range starting at the row 3, column 5 and ending at where the row 3 ends
--- -- (including the newline at the end of line 3).
---
--- -- Operators are overloaded for comparing two `vim.Pos` objects.
--- if range1 == range2 then
---   print("range1 and range2 are the same range")
--- end
--- ```
---
---@class vim.Range
---@field start_row integer 0-based byte index.
---@field start_col integer 0-based byte index.
---@field end_row integer 0-based byte index.
---@field end_col integer 0-based byte index.
---@field buf integer Optional buffer handle.
---@field private [1] integer underlying representation of start_row
---@field private [2] integer underlying representation of start_col
---@field private [3] integer underlying representation of end_row
---@field private [4] integer underlying representation of end_col
---@field private [5] integer underlying representation of buf
local M = {}

---@private
---@param pos vim.Range
---@param key any
function M.__index(pos, key)
  if key == 'start_row' then
    return pos[1]
  elseif key == 'start_col' then
    return pos[2]
  elseif key == 'end_row' then
    return pos[3]
  elseif key == 'end_col' then
    return pos[4]
  elseif key == 'buf' then
    return pos[5]
  end

  return M[key]
end

---@package
---@overload fun(start: vim.Pos, end_: vim.Pos): vim.Range
---@overload fun(buf: integer, start_row: integer, start_col: integer, end_row: integer, end_col: integer): vim.Range
function M.new(...)
  ---@type integer, integer, integer, integer, integer|nil
  local start_row, start_col, end_row, end_col, buf

  local nargs = select('#', ...)
  if nargs == 2 then
    ---@type vim.Pos, vim.Pos
    local start, end_ = ...
    validate('start', start, 'table')
    validate('end_', end_, 'table')

    if start.buf ~= end_.buf then
      error('start and end positions must belong to the same buffer')
    end
    start_row, start_col, end_row, end_col, buf = start[1], start[2], end_[1], end_[2], start.buf
  elseif nargs == 5 then
    ---@type integer, integer, integer, integer, integer
    buf, start_row, start_col, end_row, end_col = ...
    validate('buf', buf, 'number')
    validate('start_row', start_row, 'number')
    validate('start_col', start_col, 'number')
    validate('end_row', end_row, 'number')
    validate('end_col', end_col, 'number')
  else
    error('invalid parameters')
  end

  if buf == 0 then
    buf = api.nvim_get_current_buf()
  end

  ---@type vim.Range
  local self = setmetatable({
    start_row,
    start_col,
    end_row,
    end_col,
    buf,
  }, M)

  return self
end

--- TODO(ofseed): Make it work for unloaded buffers. Check get_line() in vim.lsp.util.
---@param buf integer
---@param row integer
local function get_line(buf, row)
  return api.nvim_buf_get_lines(buf, row, row + 1, true)[1]
end

---@param p1_row integer Row of first position to compare.
---@param p1_col integer Col of first position to compare.
---@param p2_row integer Row of second position to compare.
---@param p2_col integer Col of second position to compare.
---@return integer
--- 1: a > b
--- 0: a == b
--- -1: a < b
local function cmp_pos(p1_row, p1_col, p2_row, p2_col)
  if p1_row == p2_row then
    if p1_col > p2_col then
      return 1
    elseif p1_col < p2_col then
      return -1
    else
      return 0
    end
  elseif p1_row > p2_row then
    return 1
  end

  return -1
end

---@param row integer
---@param col integer
---@param buf integer
---@return integer, integer
local function to_inclusive_pos(buf, row, col)
  if col > 0 then
    col = col - 1
  elseif col == 0 and row > 0 then
    row = row - 1
    col = #get_line(buf, row)
  end

  return row, col
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function M.__lt(r1, r2)
  if r1:is_empty() then
    return cmp_pos(r1[3], r1[4], r2[1], r2[2]) ~= 1
  end

  local r1_inclusive_end_row, r1_inclusive_end_col = to_inclusive_pos(r1.buf, r1[3], r1[4])
  return cmp_pos(r1_inclusive_end_row, r1_inclusive_end_col, r2[1], r2[2]) == -1
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function M.__le(r1, r2)
  if r1:is_empty() then
    return cmp_pos(r1[3], r1[4], r2[1], r2[2]) ~= 1
  end

  local r1_inclusive_end_row, r1_inclusive_end_col = to_inclusive_pos(r1.buf, r1[3], r1[4])
  return cmp_pos(r1_inclusive_end_row, r1_inclusive_end_col, r2[1], r2[2]) ~= 1
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function M.__eq(r1, r2)
  return cmp_pos(r1[1], r1[2], r2[1], r2[2]) == 0 and cmp_pos(r1[3], r1[4], r2[3], r2[4]) == 0
end

--- Checks whether the given range is empty; i.e., start >= end.
---
---@param range vim.Range
---@return boolean `true` if the given range is empty.
function M.is_empty(range)
  return cmp_pos(range[1], range[2], range[3], range[4]) ~= -1
end

--- Checks whether {outer} range contains {inner} range or position.
---
---@param outer vim.Range
---@param inner vim.Range|vim.Pos
---@return boolean `true` if {outer} range fully contains {inner} range or position.
function M.has(outer, inner)
  if getmetatable(inner) == vim.pos then
    ---@cast inner -vim.Range
    return cmp_pos(outer[1], outer[2], inner[1], inner[2]) ~= 1
      and cmp_pos(outer[3], outer[4], inner[1], inner[2]) ~= -1
  end
  ---@cast inner -vim.Pos

  if outer:is_empty() then
    return false
  end

  -- accounts for empty ranges at the start/end of `outer` that per Neovim API and LSP logic insert
  -- the text outside `outer`
  if
    (
      cmp_pos(outer[1], outer[2], inner[3], inner[4]) ~= -1
      or cmp_pos(outer[3], outer[4], inner[1], inner[2]) ~= 1
    ) and inner:is_empty()
  then
    return false
  end

  return cmp_pos(outer[1], outer[2], inner[1], inner[2]) ~= 1
    and cmp_pos(outer[3], outer[4], inner[3], inner[4]) ~= -1
end

--- Computes the common range shared by the given ranges.
---
---@param r1 vim.Range First range to intersect.
---@param r2 vim.Range Second range to intersect
---@return vim.Range? range that is present inside both `r1` and `r2`.
---                   `nil` if such range does not exist.
function M.intersect(r1, r2)
  if r1.buf ~= r2.buf then
    return nil
  end
  if r1:is_empty() or r2:is_empty() then
    return nil
  end

  local r1_inclusive_end_row, r1_inclusive_end_col = to_inclusive_pos(r1.buf, r1[3], r1[4])
  local r2_inclusive_end_row, r2_inclusive_end_col = to_inclusive_pos(r2.buf, r2[3], r2[4])

  if
    cmp_pos(r1_inclusive_end_row, r1_inclusive_end_col, r2[1], r2[2]) ~= 1
    or cmp_pos(r1[1], r1[2], r2_inclusive_end_row, r2_inclusive_end_col) ~= -1
  then
    return nil
  end

  local rs = cmp_pos(r1[1], r1[2], r2[1], r2[2]) ~= 1 and r2 or r1
  local re = cmp_pos(r1[3], r1[4], r2[3], r2[4]) ~= -1 and r2 or r1
  return M.new(r1.buf, rs[1], rs[2], re[3], re[4])
end

--- Converts |vim.Range| to `lsp.Range`.
---
--- Example:
--- ```lua
--- local range = vim.range(0, 3, 5, 4, 0)
---
--- -- Convert to LSP range, you can call it in a method style.
--- local lsp_range = range:to_lsp('utf-16')
--- ```
---@param range vim.Range
---@param position_encoding lsp.PositionEncodingKind
---@return lsp.Range
function M.to_lsp(range, position_encoding)
  validate('range', range, 'table')
  validate('position_encoding', position_encoding, 'string', true)

  ---@type lsp.Range
  return {
    ['start'] = vim.pos(range.buf, range[1], range[2]):to_lsp(position_encoding),
    ['end'] = vim.pos(range.buf, range[3], range[4]):to_lsp(position_encoding),
  }
end

--- Creates a new |vim.Range| from `lsp.Range`.
---
--- Example:
--- ```lua
--- local lsp_range = {
---   ['start'] = { line = 3, character = 5 },
---   ['end'] = { line = 4, character = 0 }
--- }
---
--- local range = vim.range.lsp(0, lsp_range, 'utf-16')
--- ```
---@param buf integer
---@param range lsp.Range
---@param position_encoding lsp.PositionEncodingKind
function M.lsp(buf, range, position_encoding)
  validate('buf', buf, 'number')
  validate('range', range, 'table')
  validate('position_encoding', position_encoding, 'string')

  if buf == 0 then
    buf = api.nvim_get_current_buf()
  end

  -- TODO(ofseed): avoid using `Pos:lsp()` here,
  -- as they need reading files separately if buffer is unloaded.
  local start = vim.pos.lsp(buf, range['start'], position_encoding)
  local end_ = vim.pos.lsp(buf, range['end'], position_encoding)

  return M.new(start, end_)
end

--- Converts |vim.Range| to extmark range (see |api-indexing|).
---
--- Example:
--- ```lua
--- local range = vim.range(0, 3, 5, 4, 0)
---
--- -- Convert to extmark range, you can call it in a method style.
--- local extmark_range = range:to_extmark()
--- ```
---@param range vim.Range
function M.to_extmark(range)
  validate('range', range, 'table')

  local srow, scol = vim.pos(range.buf, range[1], range[2]):to_extmark()
  local erow, ecol = vim.pos(range.buf, range[3], range[4]):to_extmark()
  return srow, scol, erow, ecol
end

--- Creates a new |vim.Range| from extmark range (see |api-indexing|).
---
--- Example:
--- ```lua
--- local range = vim.range.extmark(0, 3, 5, 4, 0)
--- ```
---@param buf integer
---@param start_row integer
---@param start_col integer
---@param end_row integer
---@param end_col integer
function M.extmark(buf, start_row, start_col, end_row, end_col)
  validate('buf', buf, 'number')
  validate('start_row', start_row, 'number')
  validate('start_col', start_col, 'number')
  validate('end_row', end_row, 'number')
  validate('end_col', end_col, 'number')

  if buf == 0 then
    buf = api.nvim_get_current_buf()
  end

  local start = vim.pos.extmark(buf, start_row, start_col)
  local end_ = vim.pos.extmark(buf, end_row, end_col)

  return M.new(start, end_)
end

--- Converts |vim.Range| to mark-like range (see |api-indexing|).
---
--- Example:
--- ```lua
--- local range = vim.range(0, 3, 5, 4, 0)
---
--- -- Convert to cursor range, you can call it in a method style.
--- local cursor_range = range:to_cursor()
--- ```
---@param range vim.Range
function M.to_cursor(range)
  validate('range', range, 'table')

  local srow, scol = vim.pos(range.buf, range[1], range[2]):to_cursor()
  local erow, ecol = vim.pos(range.buf, range[3], range[4]):to_cursor()
  return srow, scol, erow, ecol
end

--- Creates a new |vim.Range| from mark-like range (see |api-indexing|).
---
--- Example:
--- ```lua
--- local start = vim.api.nvim_win_get_cursor(0)
--- -- move the cursor
--- local end_ = vim.api.nvim_win_get_cursor(0)
---
--- local range = vim.range.cursor(0, start, end_)
--- ```
---@param buf integer
---@param start_pos [integer, integer]
---@param end_pos [integer, integer]
function M.cursor(buf, start_pos, end_pos)
  validate('buf', buf, 'number')
  validate('range', start_pos, 'table')
  validate('range', end_pos, 'table')

  if buf == 0 then
    buf = api.nvim_get_current_buf()
  end

  local start = vim.pos.cursor(buf, start_pos)
  local end_ = vim.pos.cursor(buf, end_pos)

  return M.new(start, end_)
end

-- Overload `Range.new` to allow calling this module as a function.
setmetatable(M, {
  __call = function(_, ...)
    return M.new(...)
  end,
})
---@cast M +fun(start: vim.Pos, end_: vim.Pos): vim.Range
---@cast M +fun(buf: integer, start_row: integer, start_col: integer, end_row: integer, end_col: integer): vim.Range

return M
