import pathlib
import json
import re


def check_markers(test_mode=False):
    """Validate markers in PinNames.h files"""
    mbed_os_root = pathlib.Path(__file__).absolute().parents[3]

    errors = []

    with (
        mbed_os_root.joinpath("targets", "targets.json")
    ).open() as targets_json_file:
        targets_json = json.load(targets_json_file)

    if test_mode:
        search_dir = pathlib.Path(__file__).parent.joinpath('test_files').absolute()
    else:
        search_dir = mbed_os_root.joinpath('targets')

    for f in search_dir.rglob("PinNames.h"):
        with open(f) as pin_names_file:
            pin_names_file_content = pin_names_file.read()

        target_list_match = re.search(
            "\/* MBED TARGET LIST: ([0-9A-Z_,* \n]+)*\/",
            pin_names_file_content
        )

        marker_target_list = []
        if target_list_match:
            marker_target_list = list(
                re.findall(
                    r"([0-9A-Z_]{3,})",
                    target_list_match.group(1),
                    re.MULTILINE,
                )
            )

        if not marker_target_list:
            print("WARNING: MBED TARGET LIST marker invalid or not found in file " + str(f))
            errors.append({ "file": str(f), "error": "marker invalid or not found"})
            continue

        for target in marker_target_list:
            target_is_valid = False
            if target in targets_json:
                target_is_valid = True
                if "public" in targets_json[target]:
                    if targets_json[target]["public"] == False:
                        target_is_valid = False
            if not target_is_valid:
                print("WARNING: MBED TARGET LIST in file " + str(f) + " includes target '" + target + "' which doesn't exist in targets.json or is not public")
                errors.append({ "file": str(f), "error": "target not found"})

    return errors