from path import Path
from commandlib import Command
import sys
import os


def hvenv():
    """Get Hvenv folder."""
    return Path(sys.executable).joinpath("..", "..").abspath()


def keypath():
    """Get the project directory by working backwards from the virtualenv python."""
    assert hvenv().joinpath("linkfile").exists()
    assert Path(hvenv().joinpath("linkfile").bytes().decode("utf8").strip()).exists()
    return Path(hvenv().joinpath("linkfile").bytes().decode("utf8").strip())


def frozenreqs():
    return Path(hvenv().joinpath("frozenreqs.txt"))


def ensure_hitchreqs_synced():
    """
    Check packages installed are in sync with what is in hitchreqs.txt.

    If not, run pip-sync and re-run this command.
    """
    if frozenreqs().exists():
        if frozenreqs().bytes().decode("utf8") == keypath().joinpath("hitchreqs.txt").bytes().decode('utf8'):
            return

    Command(hvenv().joinpath("bin", "pip-sync"))("hitchreqs.txt").in_dir(keypath()).run()
    keypath().joinpath("hitchreqs.txt").copy(frozenreqs())
    os.execvp(sys.argv[0], sys.argv)
