import pytest

from ai_testing_swarm.core.openapi_validator import validate_openapi_response


def _spec_with_schema():
    return {
        "openapi": "3.0.0",
        "info": {"title": "t", "version": "1"},
        "paths": {
            "/pets": {
                "get": {
                    "responses": {
                        "200": {
                            "description": "ok",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {"id": {"type": "integer"}},
                                        "required": ["id"],
                                    }
                                }
                            },
                        },
                        "400": {"description": "bad"},
                    }
                }
            }
        },
    }


def test_openapi_status_validation_fails_on_undeclared_status():
    spec = _spec_with_schema()
    issues = validate_openapi_response(
        spec=spec,
        path="/pets",
        method="GET",
        status_code=418,
        response_headers={"content-type": "application/json"},
        response_json={"id": 1},
    )
    assert any(i.type == "openapi_status" for i in issues)


def test_openapi_status_validation_supports_wildcard_2xx():
    spec = {
        "openapi": "3.0.0",
        "info": {"title": "t", "version": "1"},
        "paths": {"/x": {"get": {"responses": {"2XX": {"description": "ok"}}}}},
    }
    issues = validate_openapi_response(
        spec=spec,
        path="/x",
        method="GET",
        status_code=201,
        response_headers={"content-type": "application/json"},
        response_json={"ok": True},
    )
    assert not any(i.type == "openapi_status" for i in issues)


def test_openapi_schema_validation_flags_mismatch_when_jsonschema_installed():
    pytest.importorskip("jsonschema")
    spec = _spec_with_schema()

    issues = validate_openapi_response(
        spec=spec,
        path="/pets",
        method="GET",
        status_code=200,
        response_headers={"content-type": "application/json"},
        response_json={"id": "not-an-int"},
    )

    assert any(i.type == "openapi_schema" for i in issues)
