#!/usr/bin/env python

import os
import sys
from glob import glob

# If we're using Python 2, that means that direnv has not been activated
if sys.version_info.major < 3:
    sys.stderr.write(
        "ERROR: You're running an invalid Python version. This is likely because you have pulled\n"
        "new changes that modify .envrc, and you must execute: `direnv allow`\n"
        "To re-enter the sentry Python virtual environment\n"
    )
    sys.exit(1)

try:
    import sentry_sdk

    if not os.environ.get("SENTRY_DEVENV_NO_REPORT"):
        sentry_sdk.init(dsn="https://9bdb053cb8274ea69231834d1edeec4c@o1.ingest.sentry.io/5723503")
except ModuleNotFoundError:
    sys.stdout.write(
        "WARNING: Sentry SDK not installed, thus, errors will not be reported. Run: make install-py-dev\n"
    )

text_type = str

# git usurps your bin path for hooks and will always run system python
if "VIRTUAL_ENV" in os.environ:
    # If pre-commit is not installed outside of the virtualenv, glob will return []
    try:
        site_packages = glob("%s/lib/*/site-packages" % os.environ["VIRTUAL_ENV"])[0]
        sys.path.insert(0, site_packages)
    except IndexError:
        pass


def main():
    try:
        from sentry.lint.engine import get_modified_files, run
    except ModuleNotFoundError:
        if "VIRTUAL_ENV" not in os.environ:
            sys.stderr.write(
                "ERROR: You're executing outside of the venv. Try this command: direnv allow\n"
            )
            sys.exit(1)

        sys.stdout.write("ERROR: You may be able to fix this by executing: make install-py-dev.\n")

        raise

    files_modified = [text_type(f) for f in get_modified_files(os.getcwd()) if os.path.exists(f)]

    return run(files_modified)


if __name__ == "__main__":
    sys.exit(main())