import stat
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BOOTSTRAP = ROOT / "bootstrap.sh"


def test_posix_syntax():
    assert subprocess.run(["sh", "-n", str(BOOTSTRAP)]).returncode == 0


def test_executable_bit():
    assert BOOTSTRAP.stat().st_mode & stat.S_IXUSR


def test_never_touches_the_user_profile():
    """L'invariant : aucun fichier de demarrage de shell n'est modifie."""
    content = BOOTSTRAP.read_text()
    assert "UV_NO_MODIFY_PATH=1" in content
    for profile in (".zshrc", ".bashrc", ".profile", "config.fish"):
        assert f">> {profile}" not in content
        assert f'>>"{profile}"' not in content


def _stub_env(tmp_path, *, brew=True, uv=True):
    stubs = tmp_path / "bin"
    stubs.mkdir()
    if brew:
        (stubs / "brew").write_text("#!/bin/sh\nexit 0\n")
    if uv:
        (stubs / "uv").write_text(
            f'#!/bin/sh\nprintf \'%s \' "$@" > "{tmp_path}/uv-args"\nexit 0\n'
        )
    # Tout telechargement pendant le test est une erreur : le script ne doit
    # rien installer quand les binaires sont deja la.
    (stubs / "curl").write_text("#!/bin/sh\nexit 97\n")
    for f in stubs.iterdir():
        f.chmod(0o755)
    return {"PATH": f"{stubs}:/usr/bin:/bin", "HOME": str(tmp_path)}


def test_idempotent_when_everything_is_present(tmp_path):
    env = _stub_env(tmp_path)
    result = subprocess.run(
        ["sh", str(BOOTSTRAP), "doctor"], env=env, capture_output=True, text=True
    )
    assert result.returncode == 0, result.stderr
    assert "brew : trouve" in result.stdout
    assert "uv : trouve" in result.stdout

    args = (tmp_path / "uv-args").read_text()
    assert "run" in args
    assert "machine-backup doctor" in args


def test_forwards_all_arguments(tmp_path):
    env = _stub_env(tmp_path)
    subprocess.run(
        ["sh", str(BOOTSTRAP), "restore", "latest", "--apply"],
        env=env,
        capture_output=True,
        text=True,
    )
    args = (tmp_path / "uv-args").read_text()
    assert "restore latest --apply" in args


def test_detects_uv_provided_by_mise(tmp_path):
    env = _stub_env(tmp_path, uv=False)
    mise_dir = tmp_path / ".local" / "bin"
    mise_dir.mkdir(parents=True)
    uv_dir = tmp_path / "mise-uv"
    uv_dir.mkdir()
    (uv_dir / "uv").write_text(
        f'#!/bin/sh\nprintf \'%s \' "$@" > "{tmp_path}/uv-args"\nexit 0\n'
    )
    (uv_dir / "uv").chmod(0o755)
    (mise_dir / "mise").write_text(f'#!/bin/sh\nprintf "{uv_dir}/uv\\n"\nexit 0\n')
    (mise_dir / "mise").chmod(0o755)

    result = subprocess.run(
        ["sh", str(BOOTSTRAP), "doctor"], env=env, capture_output=True, text=True
    )
    assert result.returncode == 0, result.stderr
    assert "uv : trouve via mise" in result.stdout
    assert "machine-backup doctor" in (tmp_path / "uv-args").read_text()
