from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary
import argparse
import os
import json
import re

def search_text_in_files_recursivly(base_directory, search_text, file_extension=None): 
    matches = []
    pattern = re.compile(search_text)

    for root, _, files in os.walk(base_directory):
        for file in files:
            if file_extension and not file.endswith(file_extension):
                continue
            file_path = os.path.join(root, file)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    for _, line in enumerate(f, start=1):
                        if pattern.search(line):
                            matches.append(line.strip())
            except (UnicodeDecodeError, FileNotFoundError) as e:
                exit_on_error_and_write_summary(f"Error reading {file_path}: {e}")
    return matches

def validate_params(keys_dict, reletive_path):
    logger.info(f"Validating in {reletive_path} the following values {keys_dict}")
    for key, value in keys_dict.items():
        matches = search_text_in_files_recursivly(os.path.join(os.getcwd(),reletive_path), key )
        for match in matches:
            if (": " in match or "= " in match) and not "${" in match and not "[" in match: # These chars indicate that the value is a variable 
                split_str = re.split('=|:', match, maxsplit=1)
                match_value = split_str[1].replace('"', '').replace(",", '').strip()
                match_key = split_str[0].strip()
                if match_value != value and match_key == key:
                    exit_on_error_and_write_summary(f"There is a mismatch between a local value to the one in the Secret manager \nError: {match_value}  is not equal to {value}")
                else:
                    logger.info(f"Succefully validated values {key, value} to {match_value}")

if __name__ == "__main__":
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description="Get input parameters")
    parser.add_argument('--json_string', type=str, nargs='?', help='JSON string with keys and values to search')
    parser.add_argument('--reletive_repo_path', type=str, nargs='?', help='JSON string with keys and values to search')

    args = parser.parse_args()
    
    keys_dict = json.loads(args.json_string.replace('\\n',''))
    validate_params(keys_dict, args.reletive_repo_path)