---@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(vim.api.nvim_get_current_buf(), 3, 5)
--- local pos2 = vim.pos(vim.api.nvim_get_current_buf(), 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(vim.api.nvim_get_current_buf(), 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.row, start.col, end_.row, end_.col, start.buf
  elseif nargs == 5 then
    ---@type integer, integer, integer, integer, integer
    buf, start_row, start_col, end_row, end_col = ...
  else
    error('invalid parameters')
  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)
  local r1_inclusive_end_row, r1_inclusive_end_col =
    to_inclusive_pos(r1.buf, r1.end_row, r1.end_col)
  return cmp_pos(r1_inclusive_end_row, r1_inclusive_end_col, r2.start_row, r2.start_col) == -1
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function M.__le(r1, r2)
  local r1_inclusive_end_row, r1_inclusive_end_col =
    to_inclusive_pos(r1.buf, r1.end_row, r1.end_col)
  return cmp_pos(r1_inclusive_end_row, r1_inclusive_end_col, r2.start_row, r2.start_col) ~= 1
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function M.__eq(r1, r2)
  return cmp_pos(r1.start_row, r1.start_col, r2.start_row, r2.start_col) == 0
    and cmp_pos(r1.end_row, r1.end_col, r2.end_row, r2.end_col) == 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)
  local inclusive_end_row, inclusive_end_col =
    to_inclusive_pos(range.buf, range.end_row, range.end_col)

  return cmp_pos(range.start_row, range.start_col, inclusive_end_row, inclusive_end_col) ~= -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.start_row, outer.start_col, inner.row, inner.col) ~= 1
      and cmp_pos(outer.end_row, outer.end_col, inner.row, inner.col) ~= -1
  end
  ---@cast inner -vim.Pos

  local outer_inclusive_end_row, outer_inclusive_end_col =
    to_inclusive_pos(outer.buf, outer.end_row, outer.end_col)
  local inner_inclusive_end_row, inner_inclusive_end_col =
    to_inclusive_pos(inner.buf, inner.end_row, inner.end_col)

  return cmp_pos(outer.start_row, outer.start_col, inner.start_row, inner.start_col) ~= 1
    and cmp_pos(outer.end_row, outer.end_col, inner.end_row, inner.end_col) ~= -1
    -- accounts for empty ranges at the start/end of `outer` that per Neovim API and LSP logic
    -- insert the text outside `outer`
    and cmp_pos(outer.start_row, outer.start_col, inner_inclusive_end_row, inner_inclusive_end_col) == -1
    and cmp_pos(
        outer_inclusive_end_row,
        outer_inclusive_end_col,
        inner.start_row,
        inner.start_col
      )
      == 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

  local r1_inclusive_end_row, r1_inclusive_end_col =
    to_inclusive_pos(r1.buf, r1.end_row, r1.end_col)
  local r2_inclusive_end_row, r2_inclusive_end_col =
    to_inclusive_pos(r2.buf, r2.end_row, r2.end_col)

  if
    cmp_pos(r1_inclusive_end_row, r1_inclusive_end_col, r2.start_row, r2.start_col) ~= 1
    or cmp_pos(r1.start_row, r1.start_col, r2_inclusive_end_row, r2_inclusive_end_col) ~= -1
  then
    return nil
  end

  local rs = cmp_pos(r1.start_row, r1.start_col, r2.start_row, r2.start_col) ~= 1 and r2 or r1
  local re = cmp_pos(r1.end_row, r1.end_col, r2.end_row, r2.end_col) ~= -1 and r2 or r1
  return M.new(r1.buf, rs.start_row, rs.start_col, re.end_row, re.end_col)
end

--- Converts |vim.Range| to `lsp.Range`.
---
--- Example:
--- ```lua
--- local buf = vim.api.nvim_get_current_buf()
--- local range = vim.range(buf, 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.start_row, range.start_col):to_lsp(position_encoding),
    ['end'] = vim.pos(range.buf, range.end_row, range.end_col):to_lsp(position_encoding),
  }
end

--- Creates a new |vim.Range| from `lsp.Range`.
---
--- Example:
--- ```lua
--- local buf = vim.api.nvim_get_current_buf()
--- local lsp_range = {
---   ['start'] = { line = 3, character = 5 },
---   ['end'] = { line = 4, character = 0 }
--- }
---
--- local range = vim.range.lsp(buf, 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')

  -- 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 buf = vim.api.nvim_get_current_buf()
--- local range = vim.range(buf, 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.start_row, range.start_col):to_extmark()
  local erow, ecol = vim.pos(range.buf, range.end_row, range.end_col):to_extmark()
  return srow, scol, erow, ecol
end

--- Creates a new |vim.Range| from extmark range (see |api-indexing|).
---
--- Example:
--- ```lua
--- local buf = vim.api.nvim_get_current_buf()
---
--- local range = vim.range.extmark(buf, 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')

  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 buf = vim.api.nvim_get_current_buf()
--- local range = vim.range(buf, 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.start_row, range.start_col):to_cursor()
  local erow, ecol = vim.pos(range.buf, range.end_row, range.end_col):to_cursor()
  return srow, scol, erow, ecol
end

--- Creates a new |vim.Range| from mark-like range (see |api-indexing|).
---
--- Example:
--- ```lua
--- local buf = vim.api.nvim_get_current_buf()
--- 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(buf, 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')

  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
