{
  "openapi": "3.1.0",
  "info": {
    "title": "Pearmedica Medical Intelligence API",
    "description": "AI-powered clinical decision support API for Africa.\n\nPearmedica provides state-of-the-art medical assessments using a hybrid\nRAG + LLM pipeline (OpenAI GPT-4.0 primary) combined\nwith Africa-specific medical knowledge, triage guidance, and\nnearest-facility lookup.\n\n## Authentication\nAll endpoints require API key authentication via the `Authorization` header:\n```\nAuthorization: Bearer sk_live_xxxxx\n```\n\n## Rate Limiting\nRate limits are per-API-key. Response headers include:\n- `X-RateLimit-Limit` — Maximum requests per window\n- `X-RateLimit-Remaining` — Requests remaining\n- `X-RateLimit-Reset` — Unix timestamp when the window resets\n\n## Environments\nUse `X-Pearmedica-Environment: sandbox` for testing (default: `production`).\n",
    "version": "1.0.0",
    "contact": {
      "name": "Pearmedica Engineering",
      "email": "engineering@pearmedica.com"
    },
    "license": {
      "name": "Proprietary",
      "url": "https://pearmedica.com/terms"
    }
  },
  "servers": [
    {
      "url": "https://pearmedica.vercel.app/api/v1",
      "description": "Production"
    },
    {
      "url": "http://localhost:3000/api/v1",
      "description": "Local Development"
    }
  ],
  "security": [
    {
      "BearerAuth": []
    }
  ],
  "tags": [
    {
      "name": "Assessment",
      "description": "Core medical assessment pipeline"
    },
    {
      "name": "NLP",
      "description": "Natural language processing for symptom extraction"
    },
    {
      "name": "Reference Data",
      "description": "Medical reference data (symptoms, conditions, risk factors, lab tests)"
    },
    {
      "name": "Education",
      "description": "Patient education content"
    },
    {
      "name": "Rationale",
      "description": "Assessment explainability"
    },
    {
      "name": "Usage",
      "description": "API usage analytics and billing"
    },
    {
      "name": "Health",
      "description": "Service health monitoring"
    }
  ],
  "paths": {
    "/assess": {
      "post": {
        "operationId": "createAssessment",
        "summary": "Run Medical Assessment",
        "description": "Accepts patient symptoms and returns a structured medical assessment\nwith triage guidance, condition probabilities, and nearest facilities.\n",
        "tags": ["Assessment"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AssessmentRequest"
              },
              "example": {
                "patient": {
                  "age": 35,
                  "sex": "female",
                  "location": "Lagos, Nigeria"
                },
                "evidence": [
                  {
                    "id": "s_headache",
                    "choice_id": "present",
                    "source": "initial",
                    "severity": "moderate",
                    "duration_days": 3
                  },
                  {
                    "id": "s_fever",
                    "choice_id": "present",
                    "source": "initial"
                  }
                ],
                "risk_factors": ["rf_recent_travel_tropical"]
              }
            }
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/InterviewId"
          }
        ],
        "responses": {
          "200": {
            "description": "Assessment completed successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AssessmentResponse"
                }
              }
            },
            "headers": {
              "X-API-Version": {
                "$ref": "#/components/headers/X-API-Version"
              },
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Response-Time": {
                "$ref": "#/components/headers/X-Response-Time"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/ValidationError"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "504": {
            "$ref": "#/components/responses/GatewayTimeout"
          }
        }
      }
    },
    "/parse": {
      "post": {
        "operationId": "parseText",
        "summary": "Parse Natural Language to Evidence",
        "description": "Extracts structured symptoms and risk factors from free-form text\nusing NLP. Returns mentions with confidence and suggested evidence items.\n",
        "tags": ["NLP"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ParseRequest"
              },
              "example": {
                "text": "I have a headache and fever for 3 days, and I travelled to Lagos recently",
                "age": {
                  "value": 35
                },
                "sex": "female"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Text parsed successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ParseResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/ValidationError"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/rationale": {
      "post": {
        "operationId": "getAssessmentRationale",
        "summary": "Get Assessment Rationale",
        "description": "Returns the reasoning chain for a completed assessment, explaining\nwhy conditions were ranked and how the triage level was determined.\n",
        "tags": ["Rationale"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["assessment_id"],
                "properties": {
                  "assessment_id": {
                    "type": "string",
                    "format": "uuid",
                    "description": "The ID of the assessment to explain"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Rationale generated",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RationaleResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/symptoms": {
      "get": {
        "operationId": "listSymptoms",
        "summary": "List Medical Symptoms",
        "description": "Paginated list of medical symptoms with optional search and category filter.",
        "tags": ["Reference Data"],
        "parameters": [
          {
            "$ref": "#/components/parameters/Query"
          },
          {
            "$ref": "#/components/parameters/Category"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "$ref": "#/components/parameters/Offset"
          }
        ],
        "responses": {
          "200": {
            "description": "Symptoms retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/SymptomListItem"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/risk-factors": {
      "get": {
        "operationId": "listRiskFactors",
        "summary": "List Risk Factors",
        "tags": ["Reference Data"],
        "parameters": [
          {
            "$ref": "#/components/parameters/Query"
          },
          {
            "$ref": "#/components/parameters/Category"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "$ref": "#/components/parameters/Offset"
          }
        ],
        "responses": {
          "200": {
            "description": "Risk factors retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/RiskFactorListItem"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/lab-tests": {
      "get": {
        "operationId": "listLabTests",
        "summary": "List Lab Tests",
        "tags": ["Reference Data"],
        "parameters": [
          {
            "$ref": "#/components/parameters/Query"
          },
          {
            "$ref": "#/components/parameters/Category"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "$ref": "#/components/parameters/Offset"
          }
        ],
        "responses": {
          "200": {
            "description": "Lab tests retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/LabTestListItem"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/conditions/{id}": {
      "get": {
        "operationId": "getCondition",
        "summary": "Get Condition Details",
        "tags": ["Reference Data"],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The concept ID of the condition"
          }
        ],
        "responses": {
          "200": {
            "description": "Condition details retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ConditionDetail"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/conditions/{id}/education": {
      "get": {
        "operationId": "getConditionEducation",
        "summary": "Get Patient Education for Condition",
        "description": "Returns educational content about a condition, including\nRAG-sourced knowledge from the Africa-specific medical knowledge base.\n",
        "tags": ["Education"],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The concept ID of the condition"
          }
        ],
        "responses": {
          "200": {
            "description": "Education content retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EducationResponse"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    },
    "/usage": {
      "get": {
        "operationId": "getUsageStats",
        "summary": "Get Usage Statistics",
        "description": "Aggregated API usage stats scoped to the authenticated tenant.",
        "tags": ["Usage"],
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^\\d{4}-\\d{2}-\\d{2}$"
            },
            "description": "Start date (YYYY-MM-DD)"
          },
          {
            "name": "end_date",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^\\d{4}-\\d{2}-\\d{2}$"
            },
            "description": "End date (YYYY-MM-DD)"
          }
        ],
        "responses": {
          "200": {
            "description": "Usage stats retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UsageStats"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/health": {
      "get": {
        "operationId": "healthCheck",
        "summary": "Health Check",
        "description": "Returns the health status of all platform services (database, Redis, API).\nDoes NOT require authentication. IP-rate-limited (120 req/min).\n",
        "tags": ["Health"],
        "security": [],
        "responses": {
          "200": {
            "description": "All services healthy",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthResponse"
                }
              }
            }
          },
          "503": {
            "description": "One or more services degraded",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthResponse"
                }
              }
            }
          }
        }
      }
    },
    "/search": {
      "get": {
        "operationId": "searchKnowledge",
        "summary": "Knowledge Search",
        "description": "Fuzzy text search across medical symptoms, conditions, and risk factors using PostgreSQL trigram similarity. Returns unified results ranked by relevance.\n",
        "tags": ["Reference Data"],
        "parameters": [
          {
            "name": "phrase",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 200
            },
            "description": "Search query string"
          },
          {
            "name": "sex",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": ["male", "female", "other"]
            },
            "description": "Optional sex filter for sex-specific symptoms"
          },
          {
            "name": "max_results",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 20,
              "default": 8
            },
            "description": "Maximum results to return"
          }
        ],
        "responses": {
          "200": {
            "description": "Search results retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SearchResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/ValidationError"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/fhir/assess": {
      "post": {
        "operationId": "fhirAssessment",
        "summary": "FHIR R4 Assessment",
        "description": "FHIR R4-compatible assessment endpoint. Accepts a FHIR Bundle containing Patient and Observation resources, runs through the same assessment pipeline as the proprietary endpoint, and returns a FHIR Bundle with DiagnosticReport, Condition, and DetectedIssue resources.\n",
        "tags": ["Assessment"],
        "parameters": [
          {
            "$ref": "#/components/parameters/InterviewId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/fhir+json": {
              "schema": {
                "$ref": "#/components/schemas/FhirBundle"
              },
              "example": {
                "resourceType": "Bundle",
                "type": "collection",
                "entry": [
                  {
                    "resource": {
                      "resourceType": "Patient",
                      "gender": "female",
                      "birthDate": "1998-01-01"
                    }
                  },
                  {
                    "resource": {
                      "resourceType": "Observation",
                      "code": {
                        "coding": [
                          {
                            "system": "http://pearmedica.com/symptoms",
                            "code": "s_fever"
                          }
                        ]
                      },
                      "valueString": "present"
                    }
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "FHIR assessment completed successfully",
            "content": {
              "application/fhir+json": {
                "schema": {
                  "$ref": "#/components/schemas/FhirBundle"
                }
              }
            },
            "headers": {
              "X-API-Version": {
                "$ref": "#/components/headers/X-API-Version"
              },
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Response-Time": {
                "$ref": "#/components/headers/X-Response-Time"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/ValidationError"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "422": {
            "description": "FHIR Bundle could not be translated to assessment input",
            "content": {
              "application/fhir+json": {
                "schema": {
                  "$ref": "#/components/schemas/OperationOutcome"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "504": {
            "$ref": "#/components/responses/GatewayTimeout"
          }
        }
      }
    },
    "/fhir/metadata": {
      "get": {
        "operationId": "fhirCapabilityStatement",
        "summary": "FHIR Capability Statement",
        "description": "Returns PearMedica's FHIR R4 CapabilityStatement, enabling integration engines to auto-discover supported resources, operations, and search parameters. Per the FHIR specification, this endpoint is publicly accessible without authentication.\n",
        "tags": ["Health"],
        "security": [],
        "responses": {
          "200": {
            "description": "CapabilityStatement returned",
            "content": {
              "application/fhir+json": {
                "schema": {
                  "$ref": "#/components/schemas/FhirCapabilityStatement"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "BearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "sk_live_xxxxx",
        "description": "API key issued by Pearmedica"
      }
    },
    "parameters": {
      "InterviewId": {
        "name": "X-Interview-Id",
        "in": "header",
        "required": false,
        "schema": {
          "type": "string",
          "format": "uuid"
        },
        "description": "Optional interview session ID for multi-turn conversations"
      },
      "Query": {
        "name": "query",
        "in": "query",
        "required": false,
        "schema": {
          "type": "string",
          "maxLength": 200
        },
        "description": "Search query for filtering results"
      },
      "Category": {
        "name": "category",
        "in": "query",
        "required": false,
        "schema": {
          "type": "string",
          "maxLength": 50
        },
        "description": "Category filter"
      },
      "Limit": {
        "name": "limit",
        "in": "query",
        "required": false,
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 50,
          "default": 20
        },
        "description": "Maximum results to return"
      },
      "Offset": {
        "name": "offset",
        "in": "query",
        "required": false,
        "schema": {
          "type": "integer",
          "minimum": 0,
          "default": 0
        },
        "description": "Number of results to skip"
      }
    },
    "headers": {
      "X-API-Version": {
        "description": "API version",
        "schema": {
          "type": "string",
          "example": "1.0"
        }
      },
      "X-Request-Id": {
        "description": "Unique request identifier (UUID)",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "X-Response-Time": {
        "description": "Server processing time",
        "schema": {
          "type": "string",
          "example": "1234ms"
        }
      }
    },
    "responses": {
      "ValidationError": {
        "description": "Request validation failed",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ApiError"
            },
            "example": {
              "error": {
                "code": "VALIDATION_ERROR",
                "message": "At least one evidence item is required"
              }
            }
          }
        }
      },
      "Unauthorized": {
        "description": "Missing or invalid API key",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ApiError"
            },
            "example": {
              "error": {
                "code": "INVALID_API_KEY",
                "message": "API key is missing or invalid"
              }
            }
          }
        }
      },
      "RateLimited": {
        "description": "Rate limit exceeded",
        "headers": {
          "Retry-After": {
            "schema": {
              "type": "integer"
            },
            "description": "Seconds to wait before retrying"
          },
          "X-RateLimit-Limit": {
            "schema": {
              "type": "integer"
            },
            "description": "Request limit per window"
          },
          "X-RateLimit-Remaining": {
            "schema": {
              "type": "integer"
            },
            "description": "Remaining requests in window"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ApiError"
            },
            "example": {
              "error": {
                "code": "RATE_LIMIT_EXCEEDED",
                "message": "Too many requests. Please try again later."
              }
            }
          }
        }
      },
      "NotFound": {
        "description": "Resource not found",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ApiError"
            }
          }
        }
      },
      "InternalError": {
        "description": "Internal server error",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ApiError"
            }
          }
        }
      },
      "GatewayTimeout": {
        "description": "Assessment pipeline timed out",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ApiError"
            },
            "example": {
              "error": {
                "code": "GATEWAY_TIMEOUT",
                "message": "Assessment pipeline timed out after 90000ms"
              }
            }
          }
        }
      }
    },
    "schemas": {
      "AssessmentRequest": {
        "type": "object",
        "required": ["patient", "evidence"],
        "properties": {
          "patient": {
            "$ref": "#/components/schemas/PatientData"
          },
          "evidence": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Evidence"
            },
            "minItems": 1,
            "maxItems": 50
          },
          "risk_factors": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "maxItems": 30
          },
          "previous_evidence": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Evidence"
            },
            "maxItems": 30
          }
        }
      },
      "PatientData": {
        "type": "object",
        "required": ["age", "sex"],
        "properties": {
          "age": {
            "type": "integer",
            "minimum": 0,
            "maximum": 120
          },
          "sex": {
            "type": "string",
            "enum": ["male", "female", "other"]
          },
          "location": {
            "type": "string",
            "description": "Patient location for nearest-facility lookup"
          }
        }
      },
      "Evidence": {
        "type": "object",
        "required": ["id", "choice_id", "source"],
        "properties": {
          "id": {
            "type": "string",
            "description": "Symptom or risk factor concept ID"
          },
          "choice_id": {
            "type": "string",
            "enum": ["present", "absent", "unknown"]
          },
          "source": {
            "type": "string",
            "enum": ["initial", "suggest", "predefined", "red_flags"]
          },
          "duration_days": {
            "type": "integer",
            "minimum": 0
          },
          "severity": {
            "type": "string",
            "enum": ["mild", "moderate", "severe"]
          },
          "value": {
            "type": "string"
          }
        }
      },
      "ParseRequest": {
        "type": "object",
        "required": ["text"],
        "properties": {
          "text": {
            "type": "string",
            "maxLength": 2000,
            "description": "Free-form symptom description"
          },
          "age": {
            "type": "object",
            "properties": {
              "value": {
                "type": "integer",
                "minimum": 0,
                "maximum": 120
              }
            }
          },
          "sex": {
            "type": "string",
            "enum": ["male", "female", "other"]
          }
        }
      },
      "AssessmentResponse": {
        "type": "object",
        "properties": {
          "interview_id": {
            "type": "string",
            "format": "uuid"
          },
          "conditions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AssessedCondition"
            }
          },
          "triage": {
            "type": "object",
            "properties": {
              "level": {
                "type": "string",
                "enum": ["emergency", "urgent", "routine", "self-care"]
              },
              "description": {
                "type": "string"
              },
              "recommended_action": {
                "type": "string"
              },
              "timeframe": {
                "type": "string"
              },
              "recommended_specialist": {
                "type": "object",
                "nullable": true,
                "description": "Recommended specialist based on top condition and triage level",
                "properties": {
                  "id": { "type": "string" },
                  "name": { "type": "string" },
                  "reasoning": { "type": "string" },
                  "escalate_to": { "type": "string" },
                  "escalation_trigger": { "type": "string" }
                }
              },
              "recommended_channel": {
                "type": "string",
                "nullable": true,
                "description": "Recommended consultation channel based on triage level",
                "enum": [
                  "personal_visit",
                  "video_teleconsultation",
                  "audio_teleconsultation",
                  "text_teleconsultation"
                ]
              },
              "root_cause": {
                "type": "string",
                "nullable": true,
                "description": "Clinical explanation of why this triage level was assigned"
              },
              "contributing_evidence": {
                "type": "array",
                "nullable": true,
                "description": "Symptom IDs that most strongly influenced the triage level",
                "items": { "type": "string" }
              }
            }
          },
          "should_stop": {
            "type": "boolean",
            "description": "Whether the interview has gathered sufficient evidence"
          },
          "next_question": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "text": {
                "type": "string"
              },
              "explanation": {
                "type": "string"
              },
              "options": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "label": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "red_flags": {
            "type": "array",
            "deprecated": true,
            "description": "Combined red flags as flat strings. Deprecated — use red_flags_structured instead.",
            "items": {
              "type": "string"
            }
          },
          "red_flags_structured": {
            "type": "array",
            "description": "Structured red flags with severity grading and clinical reasoning",
            "items": {
              "type": "object",
              "properties": {
                "id": { "type": "string" },
                "name": { "type": "string" },
                "seriousness": {
                  "type": "string",
                  "enum": ["serious", "emergency", "emergency_ambulance"]
                },
                "root_cause": { "type": "string" }
              }
            }
          },
          "red_flags_present": {
            "type": "array",
            "description": "Red flags the patient IS currently presenting (based on reported symptoms)",
            "items": { "type": "string" }
          },
          "red_flags_watch_for": {
            "type": "array",
            "description": "Deterioration signs to MONITOR — not reported by patient but clinically relevant",
            "items": { "type": "string" }
          },
          "red_flags_watch_for_structured": {
            "type": "array",
            "description": "Structured watch-for red flags with escalation criteria",
            "items": {
              "type": "object",
              "properties": {
                "sign": { "type": "string" },
                "escalates_to": { "type": "string" },
                "action": { "type": "string" }
              }
            }
          },
          "has_emergency_evidence": {
            "type": "boolean",
            "description": "True when any evidence directly indicates an emergency"
          },
          "clinical_warnings": {
            "type": "array",
            "description": "Clinical warnings raised by the validation chain for clinician display",
            "items": {
              "type": "object",
              "properties": {
                "type": {
                  "type": "string",
                  "enum": [
                    "validation_concern",
                    "age_vulnerability",
                    "triage_mismatch",
                    "confidence_low"
                  ]
                },
                "severity": { "type": "string", "enum": ["high", "medium", "low"] },
                "message": { "type": "string" },
                "recommended_action": { "type": "string" },
                "details": { "type": "array", "items": { "type": "string" } }
              }
            }
          },
          "recommended_investigations": {
            "type": "array",
            "description": "Prioritized diagnostic investigations recommended for this assessment",
            "items": {
              "type": "object",
              "properties": {
                "priority": { "type": "integer", "description": "1 = highest priority" },
                "test_name": { "type": "string" },
                "alternative_name": { "type": "string" },
                "purpose": { "type": "string" },
                "urgency": {
                  "type": "string",
                  "enum": [
                    "immediate",
                    "within_2_hours",
                    "within_24_hours",
                    "if_negative_for_primary"
                  ]
                },
                "source": { "type": "string" },
                "differentiates": { "type": "array", "items": { "type": "string" } },
                "interpretation": { "type": "string" }
              }
            }
          },
          "treatment_guidance": {
            "type": "object",
            "description": "Treatment guidance: immediate actions + condition-specific protocols",
            "properties": {
              "immediate_actions": { "type": "array", "items": { "type": "string" } },
              "condition_specific": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "condition_name": { "type": "string" },
                    "if_confirmed": {
                      "type": "object",
                      "properties": {
                        "first_line": { "type": "string" },
                        "alternative": { "type": "string" },
                        "source": { "type": "string" }
                      }
                    }
                  }
                }
              },
              "supportive_care": { "type": "array", "items": { "type": "string" } }
            }
          },
          "referral_pathway": {
            "type": "object",
            "description": "Referral pathway criteria and pre-referral actions",
            "properties": {
              "current_level": { "type": "string" },
              "referral_criteria": { "type": "array", "items": { "type": "string" } },
              "refer_to": { "type": "string" },
              "pre_referral_actions": { "type": "array", "items": { "type": "string" } },
              "source": { "type": "string" }
            }
          },
          "nearest_facilities": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/NearestFacility"
            }
          },
          "metadata": {
            "$ref": "#/components/schemas/AssessmentMetadata"
          },
          "disclaimer": {
            "type": "string"
          }
        }
      },
      "AssessedCondition": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "probability": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          },
          "severity": {
            "type": "string",
            "enum": ["mild", "moderate", "severe", "critical"]
          },
          "common_name": {
            "type": "string"
          },
          "icd10": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "evidence_supporting": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "evidence_against": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "snomed_ct": {
            "type": "string",
            "description": "SNOMED CT concept ID for FHIR interoperability"
          },
          "source_citations": {
            "type": "array",
            "description": "References to Source N entries from the medical knowledge context",
            "items": { "type": "string" }
          },
          "rationale_one_line": {
            "type": "string",
            "description": "One-sentence clinical rationale for this condition's ranking"
          },
          "insufficient_data": {
            "type": "boolean",
            "description": "True when retrieved knowledge context does not contain sufficient evidence"
          }
        }
      },
      "NearestFacility": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "address": {
            "type": "string"
          },
          "distance_km": {
            "type": "number"
          },
          "phone": {
            "type": "string"
          },
          "type": {
            "type": "string"
          },
          "rating": {
            "type": "number"
          },
          "open_now": {
            "type": "boolean"
          }
        }
      },
      "AssessmentMetadata": {
        "type": "object",
        "properties": {
          "model_used": {
            "type": "string"
          },
          "confidence": {
            "type": "number"
          },
          "total_latency_ms": {
            "type": "integer"
          },
          "retrieval_time_ms": {
            "type": "integer"
          },
          "generation_time_ms": {
            "type": "integer"
          },
          "validation_time_ms": {
            "type": "integer"
          },
          "validation_passed": {
            "type": "boolean"
          },
          "triage_overridden": {
            "type": "boolean"
          },
          "chunks_retrieved": {
            "type": "integer"
          },
          "cache_hit": {
            "type": "boolean"
          },
          "escalation_tier": {
            "type": "integer",
            "enum": [1, 2, 3],
            "description": "1 = Emergency override fired, 2 = Clinical warnings present, 3 = All clear"
          },
          "phi_tokenized": {
            "type": "boolean",
            "description": "Whether patient demographics were de-identified before LLM processing"
          },
          "phi_age_group": {
            "type": "string",
            "description": "Generalized age group sent to LLM (e.g. adult_26_30)"
          },
          "phi_region": {
            "type": "string",
            "description": "Generalized region sent to LLM (e.g. southwest_nigeria)"
          }
        }
      },
      "ParseResponse": {
        "type": "object",
        "properties": {
          "mentions": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "orth": {
                  "type": "string"
                },
                "choice_id": {
                  "type": "string",
                  "enum": ["present", "absent", "unknown"]
                },
                "name": {
                  "type": "string"
                },
                "common_name": {
                  "type": "string"
                },
                "type": {
                  "type": "string",
                  "enum": ["symptom", "risk_factor"]
                },
                "severity": {
                  "type": "string"
                },
                "duration_days": {
                  "type": "integer"
                }
              }
            }
          },
          "obvious": {
            "type": "boolean"
          }
        }
      },
      "RationaleResponse": {
        "type": "object",
        "properties": {
          "assessment_id": {
            "type": "string",
            "format": "uuid"
          },
          "interview_id": {
            "type": "string"
          },
          "reasoning": {
            "type": "string"
          },
          "conditions": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "probability": {
                  "type": "number"
                },
                "evidence_supporting": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                },
                "evidence_against": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                },
                "explanation": {
                  "type": "string"
                }
              }
            }
          },
          "triage": {
            "type": "object",
            "properties": {
              "level": {
                "type": "string"
              },
              "rationale": {
                "type": "string"
              },
              "overridden": {
                "type": "boolean"
              },
              "override_reason": {
                "type": "string",
                "nullable": true
              }
            }
          }
        }
      },
      "EducationResponse": {
        "type": "object",
        "properties": {
          "condition_id": {
            "type": "string"
          },
          "condition_name": {
            "type": "string"
          },
          "education": {
            "type": "object",
            "properties": {
              "overview": {
                "type": "string"
              },
              "symptoms": {
                "type": "array",
                "items": {
                  "type": "string"
                }
              },
              "prevention": {
                "type": "array",
                "items": {
                  "type": "string"
                }
              },
              "treatment_overview": {
                "type": "string",
                "nullable": true
              },
              "severity": {
                "type": "string"
              },
              "icd10_code": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "knowledge_base": {
            "type": "object",
            "properties": {
              "chunks": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "text": {
                      "type": "string"
                    },
                    "summary": {
                      "type": "string",
                      "nullable": true
                    },
                    "keywords": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                }
              },
              "sources": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "title": {
                      "type": "string"
                    },
                    "source": {
                      "type": "string"
                    },
                    "country": {
                      "type": "string",
                      "nullable": true
                    },
                    "relevance_score": {
                      "type": "number"
                    }
                  }
                }
              },
              "total_chunks": {
                "type": "integer"
              }
            }
          }
        }
      },
      "SymptomListItem": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "common_name": {
            "type": "string",
            "nullable": true
          },
          "aliases": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "category": {
            "type": "string"
          },
          "common_in_africa": {
            "type": "boolean"
          }
        }
      },
      "RiskFactorListItem": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "aliases": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "category": {
            "type": "string"
          }
        }
      },
      "LabTestListItem": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "aliases": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "category": {
            "type": "string"
          }
        }
      },
      "ConditionDetail": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "prevalence": {
            "type": "object",
            "properties": {
              "global": {
                "type": "string",
                "nullable": true
              },
              "africa": {
                "type": "string",
                "nullable": true
              },
              "endemic_regions": {
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            }
          },
          "symptoms": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "severity": {
            "type": "string"
          },
          "treatment_overview": {
            "type": "string",
            "nullable": true
          },
          "prevention": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "icd10_code": {
            "type": "string",
            "nullable": true
          },
          "version": {
            "type": "integer"
          }
        }
      },
      "UsageStats": {
        "type": "object",
        "properties": {
          "period": {
            "type": "object",
            "properties": {
              "start": {
                "type": "string"
              },
              "end": {
                "type": "string"
              }
            }
          },
          "total_assessments": {
            "type": "integer"
          },
          "breakdown": {
            "type": "object",
            "properties": {
              "by_day": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "date": {
                      "type": "string"
                    },
                    "count": {
                      "type": "integer"
                    }
                  }
                }
              },
              "by_urgency": {
                "type": "object",
                "additionalProperties": {
                  "type": "integer"
                }
              },
              "top_conditions": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "name": {
                      "type": "string"
                    },
                    "count": {
                      "type": "integer"
                    }
                  }
                }
              }
            }
          },
          "cost": {
            "type": "object",
            "properties": {
              "total_naira": {
                "type": "number"
              },
              "current_tier": {
                "type": "string"
              },
              "usage_percentage": {
                "type": "number"
              }
            }
          }
        }
      },
      "HealthResponse": {
        "type": "object",
        "properties": {
          "status": {
            "type": "string",
            "enum": ["healthy", "degraded"]
          },
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "version": {
            "type": "string"
          },
          "checks": {
            "type": "object",
            "additionalProperties": {
              "type": "string",
              "enum": ["healthy", "unhealthy", "not_configured"]
            }
          },
          "latencies": {
            "type": "object",
            "additionalProperties": {
              "type": "number"
            }
          }
        }
      },
      "ApiError": {
        "type": "object",
        "properties": {
          "error": {
            "type": "object",
            "properties": {
              "code": {
                "type": "string",
                "enum": [
                  "INVALID_API_KEY",
                  "RATE_LIMIT_EXCEEDED",
                  "INSUFFICIENT_DATA",
                  "EMERGENCY_OVERRIDE",
                  "NLP_PARSE_ERROR",
                  "UNSUPPORTED_LOCATION",
                  "VALIDATION_ERROR",
                  "INTERNAL_ERROR",
                  "UNAUTHORIZED",
                  "FORBIDDEN",
                  "NOT_FOUND",
                  "GATEWAY_TIMEOUT"
                ]
              },
              "message": {
                "type": "string"
              },
              "details": {
                "type": "object"
              }
            }
          }
        }
      },
      "SearchResponse": {
        "type": "object",
        "properties": {
          "data": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "type": {
                  "type": "string",
                  "enum": ["symptom", "condition", "risk_factor"]
                },
                "category": {
                  "type": "string",
                  "nullable": true
                },
                "similarity": {
                  "type": "number",
                  "description": "Trigram similarity score (0–1)"
                }
              }
            }
          },
          "meta": {
            "type": "object",
            "properties": {
              "total": {
                "type": "integer"
              },
              "phrase": {
                "type": "string"
              },
              "timestamp": {
                "type": "string",
                "format": "date-time"
              }
            }
          }
        }
      },
      "FhirBundle": {
        "type": "object",
        "description": "FHIR R4 Bundle resource. See https://hl7.org/fhir/R4/bundle.html",
        "required": ["resourceType", "type"],
        "properties": {
          "resourceType": {
            "type": "string",
            "enum": ["Bundle"]
          },
          "type": {
            "type": "string",
            "enum": ["collection", "transaction", "batch", "searchset"]
          },
          "entry": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "resource": {
                  "type": "object",
                  "description": "A FHIR resource (Patient, Observation, RiskAssessment, etc.)"
                }
              }
            }
          }
        }
      },
      "FhirCapabilityStatement": {
        "type": "object",
        "description": "FHIR R4 CapabilityStatement. See https://hl7.org/fhir/R4/capabilitystatement.html",
        "properties": {
          "resourceType": {
            "type": "string",
            "enum": ["CapabilityStatement"]
          },
          "status": {
            "type": "string",
            "enum": ["active", "draft", "retired"]
          },
          "kind": {
            "type": "string",
            "enum": ["instance", "capability", "requirements"]
          },
          "fhirVersion": {
            "type": "string",
            "example": "4.0.1"
          },
          "format": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "rest": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "mode": {
                  "type": "string",
                  "enum": ["server", "client"]
                },
                "resource": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "type": {
                        "type": "string"
                      },
                      "interaction": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "properties": {
                            "code": {
                              "type": "string"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "OperationOutcome": {
        "type": "object",
        "description": "FHIR R4 OperationOutcome for communicating errors. See https://hl7.org/fhir/R4/operationoutcome.html",
        "properties": {
          "resourceType": {
            "type": "string",
            "enum": ["OperationOutcome"]
          },
          "issue": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "severity": {
                  "type": "string",
                  "enum": ["fatal", "error", "warning", "information"]
                },
                "code": {
                  "type": "string"
                },
                "diagnostics": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
  }
}
