import tempfile
from pathlib import Path

from brokk_code.zed_config import ExistingBrokkCodeEntryError

_AVANTE_TEMPLATE = """-- Generated by `brokk install neovim --plugin avante`
-- Requires avante.nvim to already be installed in Neovim.
-- https://github.com/yetone/avante.nvim
--
-- Load this module from your Avante setup:
-- require("avante").setup(vim.tbl_deep_extend("force", require("brokk.brokk_avante"), {}))

return {
  provider = "brokk",
  acp_providers = {
    brokk = {
      -- Uses uvx to always run the latest version of brokk
      command = "uvx",
      args = { "brokk", "acp" },
      env = {
        HOME = os.getenv("HOME"),
        PATH = os.getenv("PATH"),
      },
    },
  },
}
"""


def _default_nvim_avante_path() -> Path:
    return Path.home() / ".config" / "nvim" / "lua" / "brokk" / "brokk_avante.lua"


def _atomic_write_text(path: Path, text: str) -> None:
    with tempfile.NamedTemporaryFile(
        mode="w",
        encoding="utf-8",
        dir=path.parent,
        prefix=f".{path.name}.",
        suffix=".tmp",
        delete=False,
    ) as temp_file:
        temp_file.write(text)
        temp_path = Path(temp_file.name)

    if path.exists():
        temp_path.chmod(path.stat().st_mode)
    temp_path.replace(path)


def configure_nvim_avante_acp_settings(
    *, force: bool = False, settings_path: Path | None = None
) -> Path:
    path = settings_path or _default_nvim_avante_path()
    if path.exists() and not force:
        raise ExistingBrokkCodeEntryError(f"{path} already exists; use --force to overwrite it")

    path.parent.mkdir(parents=True, exist_ok=True)
    _atomic_write_text(path, _AVANTE_TEMPLATE)
    return path
