"""Tests for the ~/.local/bin/axi shim writer.

The shim is a tiny bash script that execs the real venv-installed axi binary,
so non-interactive SSH sessions (federation discovery) can locate axi without
filesystem-walking.
"""

from __future__ import annotations

import stat
from pathlib import Path

from axiom.extensions.builtins.install import shim as shim_mod


def _make_fake_axi(tmp_path: Path, name: str = "venv_a") -> Path:
    venv_bin = tmp_path / name / "bin"
    venv_bin.mkdir(parents=True)
    target = venv_bin / "axi"
    target.write_text("#!/usr/bin/env python3\n# fake axi\n")
    target.chmod(0o755)
    return target


def test_write_shim_creates_executable_script(tmp_path: Path) -> None:
    target = _make_fake_axi(tmp_path)
    home = tmp_path / "home"

    result = shim_mod.write_shim(target_axi=target, home_override=home)

    shim_path = home / ".local" / "bin" / "axi"
    assert shim_path.exists()
    assert shim_path.is_file()
    # Executable for owner
    mode = shim_path.stat().st_mode
    assert mode & stat.S_IXUSR
    assert mode & stat.S_IRUSR
    # Content has correct shebang and exec line
    body = shim_path.read_text()
    assert body.startswith("#!/usr/bin/env bash\n")
    assert f'exec "{target}" "$@"' in body
    assert result.written is True
    assert result.conflict is False
    assert result.path == shim_path


def test_write_shim_is_idempotent(tmp_path: Path) -> None:
    target = _make_fake_axi(tmp_path)
    home = tmp_path / "home"

    first = shim_mod.write_shim(target_axi=target, home_override=home)
    shim_path = first.path
    mtime1 = shim_path.stat().st_mtime_ns

    second = shim_mod.write_shim(target_axi=target, home_override=home)
    mtime2 = shim_path.stat().st_mtime_ns

    assert second.written is False  # no rewrite on identical content
    assert second.conflict is False
    assert mtime1 == mtime2


def test_write_shim_detects_conflict_with_different_target(tmp_path: Path) -> None:
    first_target = _make_fake_axi(tmp_path, name="venv_a")
    second_target = _make_fake_axi(tmp_path, name="venv_b")
    home = tmp_path / "home"

    shim_mod.write_shim(target_axi=first_target, home_override=home)
    result = shim_mod.write_shim(target_axi=second_target, home_override=home)

    assert result.conflict is True
    assert result.previous_target == first_target
    # By default, a conflicting write is NOT overwritten silently.
    shim_path = home / ".local" / "bin" / "axi"
    assert str(first_target) in shim_path.read_text()

    # With force=True, it overwrites.
    forced = shim_mod.write_shim(target_axi=second_target, home_override=home, force=True)
    assert forced.written is True
    assert str(second_target) in shim_path.read_text()


def test_write_shim_creates_local_bin_dir_if_missing(tmp_path: Path) -> None:
    target = _make_fake_axi(tmp_path)
    home = tmp_path / "home"
    assert not (home / ".local" / "bin").exists()

    shim_mod.write_shim(target_axi=target, home_override=home)

    assert (home / ".local" / "bin").is_dir()


def test_path_contains_local_bin_detection(tmp_path: Path) -> None:
    home = tmp_path / "home"
    local_bin = home / ".local" / "bin"
    local_bin.mkdir(parents=True)

    path_with = f"/usr/bin:{local_bin}:/bin"
    path_without = "/usr/bin:/bin"

    assert shim_mod.path_contains_local_bin(local_bin, path_env=path_with) is True
    assert shim_mod.path_contains_local_bin(local_bin, path_env=path_without) is False


def test_cli_invokes_write_shim(tmp_path: Path, capsys, monkeypatch) -> None:
    target = _make_fake_axi(tmp_path)
    home = tmp_path / "home"

    # Point resolve_current_axi at our fake target
    monkeypatch.setattr(shim_mod, "resolve_current_axi", lambda: target)
    monkeypatch.setenv("HOME", str(home))

    from axiom.extensions.builtins.install import shim_cli

    rc = shim_cli.main([])
    assert rc == 0

    shim_path = home / ".local" / "bin" / "axi"
    assert shim_path.exists()
    out = capsys.readouterr().out
    assert "axi" in out
