import json
import os
import logging

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class ConfigValidator:
    """
    Validates Genesis configuration files for structure and values.
    """

    def __init__(self, config_dir):
        """
        Initializes the ConfigValidator with the directory containing the configuration files.

        Args:
            config_dir (str): The path to the directory containing the configuration files.
        """
        self.config_dir = config_dir
        self.errors = []

    def validate_all(self):
        """
        Validates all configuration files in the specified directory.
        """
        self.errors = []  # Reset errors before each validation run
        for filename in os.listdir(self.config_dir):
            if filename.endswith(".json"):
                filepath = os.path.join(self.config_dir, filename)
                try:
                    self.validate_file(filepath)
                except Exception as e:
                    logging.error(f"Error validating {filename}: {e}")
                    self.errors.append(f"Error validating {filename}: {e}")
        return self.errors


    def validate_file(self, filepath):
        """
        Validates a single configuration file.

        Args:
            filepath (str): The path to the configuration file.
        """
        try:
            with open(filepath, 'r') as f:
                config = json.load(f)
        except FileNotFoundError:
            msg = f"File not found: {filepath}"
            logging.error(msg)
            self.errors.append(msg)
            return
        except json.JSONDecodeError as e:
            msg = f"Invalid JSON format in {filepath}: {e}"
            logging.error(msg)
            self.errors.append(msg)
            return
        except Exception as e:
             msg = f"Error reading/parsing {filepath}: {e}"
             logging.error(msg)
             self.errors.append(msg)
             return


        # Add specific validation rules here based on the expected structure
        # and values of the configuration files.  Example:

        if not isinstance(config, dict):
            msg = f"Config file {filepath} should be a dictionary."
            logging.error(msg)
            self.errors.append(msg)
            return

        if 'version' not in config:
            msg = f"Config file {filepath} missing 'version' key."
            logging.error(msg)
            self.errors.append(msg)
        else:
            if not isinstance(config['version'], str):
                 msg = f"'version' in {filepath} should be a string."
                 logging.error(msg)
                 self.errors.append(msg)
            # Add more specific version validation if needed, e.g., regex check

        if 'parameters' in config:
            if not isinstance(config['parameters'], dict):
                msg = f"'parameters' in {filepath} should be a dictionary."
                logging.error(msg)
                self.errors.append(msg)
            else:
                # Example validation of parameters
                for param_name, param_value in config['parameters'].items():
                    if not isinstance(param_name, str):
                        msg = f"Parameter name {param_name} in {filepath} should be a string."
                        logging.error(msg)
                        self.errors.append(msg)
                    # Add more parameter-specific validation based on your config

        # Add more checks for other keys and structures as required.
        logging.info(f"Config file {filepath} validation complete.")