import stat
from pathlib import Path

import pytest

from brokk_code.nvim_config import configure_nvim_codecompanion_acp_settings
from brokk_code.zed_config import ExistingBrokkCodeEntryError


def test_configure_nvim_codecompanion_acp_settings_creates_file(tmp_path) -> None:
    settings_path = tmp_path / ".config" / "nvim" / "lua" / "brokk" / "brokk_codecompanion.lua"

    written_path = configure_nvim_codecompanion_acp_settings(settings_path=settings_path)

    assert written_path == settings_path
    content = settings_path.read_text(encoding="utf-8")
    assert 'name = "brokk"' in content
    assert '"uvx"' in content
    assert '"brokk"' in content
    assert '"acp"' in content
    assert 'type = "acp"' in content


def test_configure_nvim_codecompanion_acp_settings_rejects_existing_file(tmp_path) -> None:
    settings_path = tmp_path / ".config" / "nvim" / "lua" / "brokk" / "brokk_codecompanion.lua"
    settings_path.parent.mkdir(parents=True, exist_ok=True)
    settings_path.write_text("-- existing", encoding="utf-8")

    with pytest.raises(ExistingBrokkCodeEntryError):
        configure_nvim_codecompanion_acp_settings(settings_path=settings_path)


def test_configure_nvim_codecompanion_acp_settings_force_overwrites_existing_file(
    tmp_path,
) -> None:
    settings_path = tmp_path / ".config" / "nvim" / "lua" / "brokk" / "brokk_codecompanion.lua"
    settings_path.parent.mkdir(parents=True, exist_ok=True)
    settings_path.write_text("-- existing", encoding="utf-8")

    configure_nvim_codecompanion_acp_settings(settings_path=settings_path, force=True)

    content = settings_path.read_text(encoding="utf-8")
    assert "-- Generated by `brokk install nvim`" in content


def test_configure_nvim_codecompanion_acp_settings_preserves_existing_permissions(tmp_path) -> None:
    settings_path = tmp_path / ".config" / "nvim" / "lua" / "brokk" / "brokk_codecompanion.lua"
    settings_path.parent.mkdir(parents=True, exist_ok=True)
    settings_path.write_text("-- existing", encoding="utf-8")
    settings_path.chmod(0o640)
    expected_mode = stat.S_IMODE(settings_path.stat().st_mode)

    configure_nvim_codecompanion_acp_settings(settings_path=settings_path, force=True)

    mode = stat.S_IMODE(settings_path.stat().st_mode)
    assert mode == expected_mode


def test_configure_nvim_codecompanion_acp_settings_default_path(monkeypatch, tmp_path) -> None:
    fake_home = tmp_path / "home"
    monkeypatch.setattr(Path, "home", lambda: fake_home)

    written_path = configure_nvim_codecompanion_acp_settings()

    assert (
        written_path == fake_home / ".config" / "nvim" / "lua" / "brokk" / "brokk_codecompanion.lua"
    )
    assert written_path.exists()
