import json

from .models import PortData


def generate_openapi_spec() -> str:
    """Generate an OpenAPI 3.0 specification for the mooring data output.

    Returns:
        JSON string of the OpenAPI specification
    """
    # Get the Pydantic model's JSON schema
    port_schema = PortData.model_json_schema()

    # Build OpenAPI 3.0 specification
    openapi_spec = {
        "openapi": "3.0.3",
        "info": {
            "title": "Mooring Data Generator API",
            "description": "API specification for mooring data generated by mooring-data-generator",
            "version": "1.0.0",
        },
        "paths": {
            "/": {
                "post": {
                    "summary": "Receive mooring data",
                    "description": "Endpoint that receives generated mooring data via HTTP POST",
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {"$ref": "#/components/schemas/PortData"}
                            }
                        },
                    },
                    "responses": {"200": {"description": "Successfully received mooring data"}},
                }
            }
        },
        "components": {"schemas": {}},
    }

    # Extract all schemas from the Pydantic model
    # The model_json_schema() includes all nested models in $defs
    if "$defs" in port_schema:
        openapi_spec["components"]["schemas"] = port_schema["$defs"]

    # Add the main PortData schema
    port_data_schema = {k: v for k, v in port_schema.items() if k != "$defs"}
    openapi_spec["components"]["schemas"]["PortData"] = port_data_schema

    return json.dumps(openapi_spec, indent=2)
