from enum import Enum

import yaml
from yaml.representer import BaseRepresenter

from ..model import BaseModel, OpenapiModel


def represent_base_model(rep: BaseRepresenter, data: BaseModel):
    if isinstance(data, BaseModel):
        data = data.get_model_data()
    return rep.represent_mapping("tag:yaml.org,2002:map", data)


def represent_enum(rep: BaseRepresenter, data: Enum):
    return rep.represent_scalar("tag:yaml.org,2002:str", data.value)


yaml.add_multi_representer(BaseModel, represent_base_model)
yaml.add_multi_representer(Enum, represent_enum)


def build_open_api_yaml(model: OpenapiModel) -> str:
    return yaml.dump(model, sort_keys=False)
