import os
import git
from git import Repo
import yaml
import datetime
import requests
import re

t = datetime.datetime.now()
t=t.strftime('%H%M%S')
print (t)

repo_url = 'https://github.kp.org/CSG/GlobalReleaseMgmt'
repo_path = 'p:/RRB' + t
file_path_to_check = 'Payments/walletService10152023.yaml'
file_path = f'{repo_path}/{file_path_to_check}'
required_attributes = ["appName","squadName","platform"]  # Replace with your required attributes

# Define a dictionary of attributes and their corresponding regular expressions for validation
attribute_validations = {
    'appName': r'^[a-zA-Z]+$',
    'squadName': r'^[a-zA-Z]+$',  
    'platform': r'^[a-zA-Z]+$',    
    # Add more attributes and their corresponding regular expressions as needed
}

# Define a dictionary of sample data to validate
data_to_validate = {
    'appName': 'walletservice',
    'squadName': 'payments',
    'platform': 'aks',
    # Add more attributes and their values to validate
}


# checking whether file is available or not
def is_file_in_git(file_path_to_check, repo_path):
    
    if not os.path.exists(repo_path):
        print(f"Git repository not found at {repo_path}")
        exit(1)
    try:
        repo = git.Repo(repo_path)
    except git.exc.InvalidGitRepositoryError:
        print(f"Not a valid Git repository at {repo_path}")
        exit(1)

    file_exists = os.path.isfile(os.path.join(repo_path, file_path_to_check))
    
    if file_exists:
        print(f"The file '{file_path_to_check}' exists in the Git repository.")
        return True
    else:
        print(f"The file '{file_path_to_check}' does not exist in the Git repository.")
        return False
    
# checking whether attributes are present or not 
def validate_yaml_attributes(file_path, required_attributes):
    try:
        with open(file_path, "r") as file:
            yaml_data = yaml.safe_load(file)
            missing_attributes = [attr for attr in required_attributes if attr not in yaml_data]
            if len(missing_attributes) == 0:
                return True
            else:
                return missing_attributes
    except Exception as e:
        print(f"An error occurred: {e}")
        return []

def validate_attributes_syntax(data):
    valid_attributes = []
    invalid_attributes = []
    for attribute, regex_pattern in attribute_validations.items():
        value = data.get(attribute)
        if value is not None:
            if re.match(regex_pattern, value):
                valid_attributes.append(attribute)
                
            else:
                invalid_attributes.append(attribute)

    if len(invalid_attributes) == 0:
        print("All attributes are valid.")
        return True
    else:
        print("Invalid attributes:")
        for attr in invalid_attributes:
            print(f"{attr}: {invalid_attributes[attr]}")
        return False       
# below is logic to be used when using multiple scripts
# Clone the repository
repo = Repo.clone_from(repo_url, repo_path)

if is_file_in_git(file_path_to_check, repo_path):
    print(f"The file '{file_path_to_check}' is in the Git repository.")
    # Validate attributes
    file_path = os.path.join(repo_path, file_path_to_check)
    missing_attributes = validate_yaml_attributes(file_path, required_attributes)

    if missing_attributes:
        print("The following required attributes are missing:")
        for attr in missing_attributes:
            print(f"- {attr}")
    else:
        print("All required attributes are present.")
        validate_attributes_syntax(data_to_validate)
else:
    print(f"The file '{file_path_to_check}' is not in the Git repository.")


