from __future__ import annotations

import os
import subprocess

from pathlib import Path

from poetry.core.vcs.git import Git


def get_vcs(directory: Path) -> Git | None:
    cwd = str(directory.resolve())

    vcs: Git | None

    try:
        from poetry.core.vcs.git import executable

        check_ignore = subprocess.run(
            [executable(), "check-ignore", "."],
            stderr=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
        ).returncode

        if check_ignore == 0:
            vcs = None
        else:
            git_dir = subprocess.check_output(
                [executable(), "rev-parse", "--show-prefix"],
                stderr=subprocess.STDOUT,
                text=True,
                cwd=cwd,
                encoding="utf-8",
            ).strip()
            git_dir = git_dir.strip()[:-1]  # remove the trailing os.sep
            if not git_dir:
                git_dir = cwd
            else:
                git_dir = cwd[:-len(git_dir)]

            vcs = Git(Path(git_dir))

    except (subprocess.CalledProcessError, OSError, RuntimeError):
        vcs = None

    return vcs
