from typing import Dict, Optional

from messageprocessor import MessageProcessor
from simplehttprouter import Route

from ..builder.registry import get_builder
from ..interactor.dto import AutoOpenApiYamlBuilderRequest
from ..model import ServerModel


class AutoOpenApiYamlBuilderInteractor:
    def __init__(self, routes: Optional[Dict[Route, MessageProcessor]] = None):
        self.routes = routes
        self.builder = get_builder()

    def execute(self, request: AutoOpenApiYamlBuilderRequest) -> str:
        if request.host is not None:
            self.builder.get_model().add_server(
                server=ServerModel(
                    url=request.host,
                )
            )

        if self.routes is not None:
            for route, processor in self.routes.items():
                self.builder.add_processor_path(
                    route=route,
                    processor=processor,
                )

        return self.builder.build_open_api_yaml()
