"""NativeSchemaStrategy: 阶梯①预防(D7/D14)——网关支持时用协议级约束。

请求侧注入 response_format(有 schema 用 json_schema 严格模式,无 schema
退为 json_object);响应侧仍复用修复链兜底——原生约束下模型偶发的围栏/
噪声不至于直接判死。
"""

from __future__ import annotations

from typing import Any

from polygateway.structured.json_repair import JsonRepairStrategy


class NativeSchemaStrategy:
    """response_format 注入策略;由装配层按 provider 注册表能力选择。"""

    def __init__(self) -> None:
        self._repair = JsonRepairStrategy()

    def request_overlay(self, schema: dict[str, Any] | None) -> dict[str, Any]:
        if schema is None:
            return {"response_format": {"type": "json_object"}}
        return {
            "response_format": {
                "type": "json_schema",
                "json_schema": {"name": "structured_output", "strict": True, "schema": schema},
            }
        }

    def parse(self, text: str) -> Any:
        return self._repair.parse(text)
