from pathlib import Path

import yamale

from worker_configuration.schema import build_schema


def validate(payload: dict, name="in-memory"):
    """
    Validate the structure and content of an Arkindex worker as Python dict
    """
    # Yamale needs a list of tuples to build explicit errors
    schema = build_schema()
    yamale.validate(schema, [(payload, name)])

    return True


def validate_file(path: Path):
    """
    Validate the structure and content of an Arkindex worker as YAML file
    """
    assert path.exists(), f"Missing file {path}"

    # We only support one file at a time
    # whereas yamale can process multiple payloads
    data = yamale.make_data(path)
    assert len(data) == 1, "Only one YAML payload at a time"

    # Validate file structure and content at once
    yamale.validate(build_schema(), data)

    return data[0][0]
