openapi: 3.0.3
info:
  title: LegiScan EDO Integration API
  version: 1.0.0
  description: |
    API для интеграции анализа договоров LegiScan в системы ЭДО.
    Поддерживает синхронный и асинхронный режимы, загрузку файлов, URL и чистого текста,
    а также коллбеки с HMAC‑подписью.
servers:
  - url: https://legiscan.ru
security:
  - ApiKeyAuth: []
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
  schemas:
    AnalyzeSyncResponse:
      type: object
      properties:
        result:
          description: Результат анализа (структура совпадает с веб/бот версией)
          type: object
    EnqueueResponse:
      type: object
      properties:
        id:
          type: string
        status:
          type: string
          enum: [queued]
    JobStatus:
      type: object
      properties:
        id:
          type: string
        status:
          type: string
          enum: [queued, processing, succeeded, failed]
        result:
          type: object
          nullable: true
        error:
          type: string
          nullable: true
        createdAt:
          type: integer
          format: int64
        updatedAt:
          type: integer
          format: int64
    CallbackPayload:
      type: object
      properties:
        id: { type: string }
        status: { type: string, enum: [queued, processing, succeeded, failed] }
        result: { type: object, nullable: true }
        error: { type: string, nullable: true }
paths:
  /api/edo/analyze:
    post:
      summary: Запустить анализ договора
      description: |
        Поддерживает 3 формата тела запроса:
        1) multipart/form-data — поля `file`, `url`, `text` (одно из них)
        2) application/json — `{ url | text, fileName? }`
        3) text/plain — чистый текст договора

        Режимы:
        - Синхронный (по умолчанию) — возвращает результат анализа.
        - Асинхронный (`?async=true`) — ставит задачу в очередь и возвращает `id`; опционально отправляет коллбек на `callback_url`.
      security:
        - ApiKeyAuth: []
      parameters:
        - in: query
          name: async
          schema: { type: boolean }
          description: Если true — асинхронная постановка задачи
        - in: query
          name: callback_url
          schema: { type: string, format: uri }
          description: URL для вебхука по завершении задачи
        - in: query
          name: selectedParty
          schema: { type: string }
          description: Явно указать сторону договора для анализа
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
                url:
                  type: string
                  format: uri
                text:
                  type: string
          application/json:
            schema:
              type: object
              properties:
                url: { type: string, format: uri }
                text: { type: string }
                fileName: { type: string }
          text/plain:
            schema:
              type: string
      responses:
        '200':
          description: Синхронный результат анализа
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AnalyzeSyncResponse'
        '202':
          description: Задача поставлена в очередь (асинхронный режим)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EnqueueResponse'
        '400': { description: Ошибка валидации/ввода }
        '401': { description: Неавторизовано (неверный API ключ) }
        '415': { description: Неподдерживаемый тип контента }
        '500': { description: Внутренняя ошибка }

  /api/edo/jobs/{id}:
    get:
      summary: Получить статус задачи анализа
      security:
        - ApiKeyAuth: []
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Статус задачи
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JobStatus'
        '404': { description: Задача не найдена }

  /openapi.yaml:
    get:
      summary: Статический файл OpenAPI
      responses:
        '200': { description: YAML спецификация }

webhooks:
  edoCallback:
    post:
      summary: Вебхук завершения анализа
      description: |
        LegiScan отправляет POST на `callback_url`, если он был передан при запуске задачи.
        Подпись запроса передаётся в заголовке `X-Signature` (HMAC-SHA256 по телу, секрет — `EDO_WEBHOOK_SECRET`).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CallbackPayload'
      responses:
        '200': { description: Принято }


