import yaml
import os
import logging
from collections import defaultdict


class DuplicateKeyError(Exception):
    """
    Create custom exception for duplicate keys in YAML file.
    """
    pass


class DuplicateKeySafeLoader(yaml.SafeLoader):
    """
    Extend SafeLoader from YAML loader to detect duplicate keys.
    """

    def construct_mapping(self, node, deep=False):
        """
        Override construct_mapping to detect duplicate keys in mappings.
        """
        mapping = {}
        keys = defaultdict(str)
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            if key in keys:
                line_error = f"Duplicate key '{key}' found at line {key_node.start_mark.line + 1}, "
                col_error = f"column {key_node.start_mark.column + 1}."
                logging.error(f"Ambiguous YAML detected: {line_error} {col_error}")
            keys[
                key] += "holder"  # Not value of the key because it can be a reference to a child node
            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value
        return mapping


def load_config(path):
    """
    Load a YAML file and verify for ambiguity in the fields.
    """
    try:
        with open(path) as f:
            cfg = yaml.load(f.read(), Loader=DuplicateKeySafeLoader)
            return cfg
    except yaml.YAMLError as e:
        logging.error(f"Invalid YAML format: {e}")
        return None
    except FileNotFoundError:
        raise RuntimeError(f"config file not found: {path}")
