#!/usr/bin/env python3
import sys
import re
import os

def check_env(template_path, local_path):
    try:
        with open(template_path, "r") as template, open(local_path, "r") as local:
            t_keyset = set()
            is_consistent = True
            for t_entry in template:
                if t_entry.startswith("#") or len(t_entry.strip()) == 0:
                    continue

                t_keyset.add(t_entry.split("=")[0])

            for entry in local:
                if entry.startswith("#") or len(entry.strip()) == 0:
                    continue

                kv_pair = entry.split("=")
                key = kv_pair[0]
                if len(kv_pair) < 2:
                    print(f"Value missing for the env variable {key}")
                    is_consistent = False

                if key in t_keyset:
                    t_keyset.remove(key)
                else:
                    print(f"Env variable {key} is not defined in template env file @{template_path}. Please include it in template if used.")
                    is_consistent = False

            for missing_key in t_keyset:
                print(f"Env variable {missing_key} is missing from env file @{local_path}. Please provide the entry with value.")
                is_consistent = False

            return is_consistent
    except FileNotFoundError:
        raise FileNotFoundError
    except Exception as e:
        raise e


if __name__ == "__main__":
    pattern = r'^\.env.*\.example$'
    t_envs = []
    envs = []
    for entry in os.scandir(os.getcwd()):
        if entry.is_file() and re.match(pattern, entry.name):
            t_envs.append(entry.name)
            envs.append(entry.name[:-8])

    should_exit = False
    for i in range(len(t_envs)):
        try:
            should_exit = not check_env(t_envs[i], envs[i]) or should_exit
        except FileNotFoundError:
            should_exit = True
            print(f"One or both files not found. Both the example and the local env file should be present")
        except Exception as e:
            should_exit = True
            print(f"An error occurred: {e}")

    if should_exit:
        print("Aborting push")
        sys.exit(1)