#!/usr/bin/env python3

## TODO: let it set up dev-deps for checking automatically in virtualenv

import sys
import glob
import subprocess

def run(cmd_args):
    print("+ " + " ".join(cmd_args))
    p = subprocess.run(cmd_args)
    return p.returncode == 0

checks = {
    "mypy": lambda f: ["mypy", "--ignore-missing-imports", f],
    # "flake8": lambda f: ["flake8", f, "--count", "--select=E9,F63,F7,F82", "--show-source", "--statistics"],
    "pylint": lambda f: ["pylint", "-E", f]
}


checked = []
failed = []
unknowns = []

import pickle
import hashlib #instead of md5
try:
    l = pickle.load(open("/tmp/ckdb", "rb"))
except IOError:
    l = []
db = dict(l)

def is_py(f: str):
    if f.endswith(".py"):
        return True
    with open(f, "r") as fh:
        content = fh.read()
        for line in content.split("\n"):
            if line.startswith("#!") and "python" in line:
                return True
    return False

for pat in sys.argv[1:]:
    for f in glob.glob(pat):
        checksum = hashlib.md5(open(f).read().encode('utf-8')).hexdigest()
        if db.get(f, None) == checksum:
            print(f + " is not modified")
            continue
        if is_py(f):
            if all(run(check(f)) for name, check in checks.items()):
                checked.append(f)
                db[f] = checksum
            else:
                failed.append(f)
        else:
            unknowns.append(f)

for f in checked:
    print("[ck] ✅ Checked: " + f)

for f in failed:
    print("[ck] ❌ Failed: " + f)

for f in unknowns:
    print("[ck] ❓ Ignoring unknown extension: " + f)

pickle.dump(list(db.items()), open("/tmp/ckdb", "wb"))

if len(failed):
    exit(-1)
