from __future__ import annotations

import yaml


class OpenAPIPostprocessor:
    _ALLOWED_METHODS = {"get", "post", "put", "delete", "patch"}

    def validate(self, answer: str, *, require_paths: bool) -> tuple[bool, dict]:
        try:
            payload = yaml.safe_load(answer) or {}
        except yaml.YAMLError:
            return False, {"reason": "invalid_yaml"}
        if not isinstance(payload, dict):
            return False, {"reason": "invalid_yaml_root"}
        if require_paths:
            paths = payload.get("paths")
            if not isinstance(paths, dict) or not paths:
                return False, {"reason": "missing_paths"}
            methods = self._methods(paths)
            if not methods:
                return False, {"reason": "missing_method"}
            return True, {"reason": "ok", "methods": methods}
        if not isinstance(payload, dict) or not payload:
            return False, {"reason": "empty_schema"}
        return True, {"reason": "ok"}

    def _methods(self, paths: dict) -> list[str]:
        methods: list[str] = []
        for item in paths.values():
            if not isinstance(item, dict):
                continue
            for method in item.keys():
                method_name = str(method).lower()
                if method_name in self._ALLOWED_METHODS and method_name not in methods:
                    methods.append(method_name)
        return methods
