openapi: 3.0.3
info:
  title: Genier API v3
  version: "3.11.0"
  description: |
    API v3 do Genier para interação com agentes, LLMs, TTS/STT e pipelines de áudio.
    Autenticação via chave de API no cabeçalho `Authorization`.
    Base URL: `https://app.genier.ai/{tenant}/api/v3/`
servers:
  - url: https://{host}/{tenant}
    description: Host do ambiente Genier
    variables:
      host:
        default: app.genier.ai
      tenant:
        default: my-tenant
tags:
  - name: Agentes
    description: Execução de agentes, WebChat e multicanal
  - name: Curadoria e templates
    description: Geração de templates e curadoria de conteúdo
  - name: Insights
    description: Análises e resumos de conversas
  - name: Reverse copilot
    description: Formatação de perguntas e respostas humanizadas
  - name: Autenticação e sistema
    description: Utilidades e autenticação da plataforma
  - name: Arquivos e recursos
    description: Manipulação de arquivos e recursos estáticos
  - name: Analytics e Journey
    description: Endpoints relacionados a dados de jornada e analytics
paths:
  /api/v3/agent_voice:
    post:
      summary: Gerar áudio TTS para um agente
      tags: [Agentes]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentVoiceRequest'
            example:
              text: "Olá, este é o script do bot."
              agent_id: "agent_1234abcd"
              slug: "saudacao"
      responses:
        '200':
          description: Áudio gerado com sucesso
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentVoiceResponse'
              example:
                result: ok
                message: Áudio gerado com sucesso
                public_url: /agent_voice/1234abcd/saudacao.mp3
        '400':
          description: Requisição inválida (campos obrigatórios ou TTS ausente)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Campos obrigatórios: text, agent_id, slug"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '404':
          description: Agente ou configuração TTS não encontrada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Agente não encontrado: agent_1234abcd"
        '500':
          description: Erro interno ao gerar áudio
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Erro ao gerar áudio: detalhe"

  /api/v3/agent/{agent_id}:
    post:
      summary: Executar agente (texto) com histórico
      tags: [Agentes]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: agent_id
          in: path
          required: true
          schema:
            type: string
          description: "ID do agente (ex.: agent_1234abcd)"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentRequest'
            example:
              query: "Como funciona o produto?"
              history:
                - input: "Oi"
                  output: "Olá, posso ajudar."
              tts: false
              user_prompt: "Use tom amigável"
              voice_priority: false
              ask_human: false
      responses:
        '200':
          description: Resposta do agente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentResponseData'
              example:
                status: 0
                history:
                  - output: "Olá, posso ajudar."
                  - output: "O produto funciona assim..."
                response: "O produto funciona assim..."
                entity: false
                entity_content: {}
                tts_audio_mp3_encoded_base64: "NA"
        '400':
          description: Parâmetros obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: 'query not found'
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/webchat/{agent_id}:
    post:
      summary: Executar agente para WebChat
      tags: [Agentes]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: agent_id
          in: path
          required: true
          schema:
            type: string
          description: "ID do agente (ex.: agent_1234abcd)"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebchatRequest'
            example:
              query: "Qual o status do meu pedido?"
              history:
                - input: "Oi"
                  output: "Olá, como posso ajudar?"
              tts: true
      responses:
        '200':
          description: Resposta do agente para WebChat
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentResponseData'
              example:
                status: 0
                history:
                  - output: "Olá, como posso ajudar?"
                  - output: "Seu pedido está em separação."
                response: "Seu pedido está em separação."
                entity: false
                entity_content: {}
                tts_audio_mp3_encoded_base64: "<base64>"
        '400':
          description: Parâmetros obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: 'query not found'
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/agent_mm/{agent_id}:
    post:
      summary: Executar agente multimodal (texto, áudio, OCR, upload)
      tags: [Agentes]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: agent_id
          in: path
          required: true
          schema:
            type: string
          description: "ID do agente (ex.: agent_1234abcd)"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentMMJsonRequest'
            example:
              history:
                - input: "Oi"
                  output: "Olá"
              text: "Analise o texto do PDF."
              tts: false
              hashtag: false
              ask_human: false
              user_prompt: "Resuma em bullet points"
              voice_priority: false
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/AgentMMFormRequest'
            example:
              history: '[{"input":"Oi","output":"Olá"}]'
              text: "Extraia hashtags do áudio"
              tts: "true"
              hashtag: "true"
              ask_human: "false"
              user_prompt: "Mantenha resposta curta"
              voice_priority: "false"
              session_id: "c9d5b1d4-0e3b-4a6f-9a8d-1234567890ab"
      responses:
        '200':
          description: Resposta do agente multimodal
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentResponseData'
              example:
                status: 0
                history:
                  - output: "Processado com sucesso"
                response: "Resumo do conteúdo"
                entity: true
                entity_content:
                  hashtags: ["#promo", "#lancamento"]
                tts_audio_mp3_encoded_base64: "<base64>"
                file_encoded_base64: "<base64>"
                session_id: "c9d5b1d4-0e3b-4a6f-9a8d-1234567890ab"
        '400':
          description: Parâmetros obrigatórios ausentes ou entrada inválida
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: 'history not found in JSON data'
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '403':
          description: Conteúdo não suportado para o modo do agente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Olá! No momento não consigo processar esse tipo de conteúdo. Por favor, envie uma mensagem de texto e eu continuo a te ajudar."
        '413':
          description: Arquivo muito grande
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "File too large"
        '415':
          description: Tipo de arquivo não suportado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Unsupported media type"
        '500':
          description: Erro interno ao processar conteúdo
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Erro ao processar conteúdo"

  /api/v3/agent_list:
    get:
      summary: Listar agentes disponíveis
      tags: [Agentes]
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Lista de agentes
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/AgentListItem'
              example:
                - name: "Atendimento Geral"
                  id: "agent_1234abcd"
                - name: "Suporte Técnico"
                  id: "agent_5678efgh"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/run_llm:
    post:
      summary: Executar LLM direto
      tags: ["LLM e Processamento"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RunLLMRequest'
            example:
              prompt: "Gere um resumo curto"
              payload: { "context": "Texto de entrada" }
              reasoning_effort: "medium"
              verbosity: "verbose"
      responses:
        '200':
          description: Resposta do LLM
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RunLLMResponse'
              example:
                output: "Resumo curto do texto"
                metadata: { "model": "gpt-4.1" }
        '400':
          description: Faltou prompt ou payload
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Missing 'prompt' or 'payload' in request body"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Erro interno ao executar LLM
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "error detail"

  /api/v3/generate:
    post:
      summary: Gerar texto com modelo informado
      tags: ["LLM e Processamento"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateRequest'
            example:
              model: "gpt-4.1"
              query: "Escreva um email de boas-vindas"
              session: "fb6d2f62-2a0d-4c4f-a1b5-1234567890ab"
      responses:
        '200':
          description: Texto gerado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GenerateResponse'
              example:
                response: "Olá! Bem-vindo ao nosso serviço..."
                session: "fb6d2f62-2a0d-4c4f-a1b5-1234567890ab"
        '400':
          description: Faltou model ou query
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Falta parametros, model ou query"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/generate_mem:
    post:
      summary: Gerar texto com memória de sessão
      tags: ["LLM e Processamento"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateRequest'
            example:
              model: "gpt-4.1"
              query: "Continue a conversa"
              session: "fb6d2f62-2a0d-4c4f-a1b5-1234567890ab"
      responses:
        '200':
          description: Texto gerado com memória
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GenerateResponse'
              example:
                response: "Claro, seguindo do ponto anterior..."
                session: "fb6d2f62-2a0d-4c4f-a1b5-1234567890ab"
        '400':
          description: Faltou model ou query
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Falta parametros, model ou query"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/search:
    post:
      summary: Buscar conteúdo usando modelo informado
      tags: ["LLM e Processamento"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateRequest'
            example:
              model: "gpt-4.1"
              query: "Busque conhecimento sobre produto X"
              session: "fb6d2f62-2a0d-4c4f-a1b5-1234567890ab"
      responses:
        '200':
          description: Resultado da busca/geração
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GenerateResponse'
              example:
                response: "Resultados encontrados ..."
                session: "fb6d2f62-2a0d-4c4f-a1b5-1234567890ab"
        '400':
          description: Faltou model ou query
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Falta parametros, model ou query"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/tts:
    post:
      summary: Sintetizar fala (TTS)
      tags: ["Speech e áudio"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TTSRequest'
            example:
              query: "Olá, bem-vindo ao Genier!"
              tts_config_id: "00000000-0000-0000-0000-000000000000"
      responses:
        '200':
          description: Áudio gerado em base64
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TTSResponse'
              example:
                audio_content_base64: "<base64>"
                config_used: "00000000-0000-0000-0000-000000000000"
                provider: "elevenlabs"
                model: "eleven_monolingual_v1"
                voice: "Bella"
        '400':
          description: Erro de validação (campo obrigatório ou configuração inválida)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Missing 'query' field in request"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '404':
          description: Configuração TTS não encontrada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "TTS configuration not found: <id>"
        '500':
          description: Erro interno do TTS
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "TTS Error: detalhe"

  /api/v3/stt_transcribe:
    post:
      summary: Transcrever áudio (STT)
      tags: ["Speech e áudio"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/STTTranscribeRequest'
            example:
              file: "(binário .wav/.mp3)"
              data: '{"lang":"pt-BR"}'
      responses:
        '200':
          description: Transcrição concluída
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/STTTranscribeResponse'
              example:
                source: "http://127.0.0.1:7860/static/data/abc123.wav"
                result: "texto transcrito"
        '400':
          description: Requisição inválida ou sem arquivo
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "No selected file"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Falha ao notificar ou erro interno
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Failed to notify"

  /api/v3/voiceverse:
    post:
      summary: Pipeline de áudio (transcrição + análise)
      tags: ["Speech e áudio"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/VoiceverseRequest'
            example:
              pipeline: "call_center"
              file: "(binário .wav/.mp3)"
      responses:
        '200':
          description: Resultado do pipeline de áudio
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VoiceverseResponse'
              example:
                transcribed:
                  response: "texto transcrito"
                conversation: "organização das falas"
                resume: "resumo do áudio"
                sentimental: "análise de sentimento"
        '400':
          description: Pipeline ausente/erro de configuração ou arquivo faltando
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Pipeline parameter is missing"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Erro interno ao processar ou notificar
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Failed to notify"

  /api/v3/voiceverse_list:
    get:
      summary: Listar pipelines de áudio
      tags: ["Speech e áudio"]
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Lista de pipelines
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/VoiceverseListItem'
              example:
                - pipeline_name: "call_center"
                  pipeline_id: "call_center"
                  steps: ["transcript", "organize", "resume", "sentiment"]
                - pipeline_name: "voz_para_texto"
                  pipeline_id: "voz_para_texto"
                  steps: ["transcript"]
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/voiceverse_content/{pipeline_id}:
    get:
      summary: Obter definição completa do pipeline
      tags: ["Speech e áudio"]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: pipeline_id
          in: path
          required: true
          schema:
            type: string
          description: "ID do pipeline salvo em data/pipelines (ex.: call_center)"
      responses:
        '200':
          description: Conteúdo bruto do pipeline
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VoiceverseContent'
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '404':
          description: Pipeline não encontrado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Pipeline not found
        '500':
          description: Erro ao carregar pipeline
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "ERROR <detalhe>"

  /api/v3/ocr:
    post:
      summary: Extrair texto de documento via OCR
      description: Processa PDF ou imagem, valida tamanho e número de páginas e retorna o texto extraído.
      tags: ["Processamento de arquivos (OCR)"]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/OCRRequest'
            example:
              file: "(binário .pdf/.jpg/.png)"
              lang: "por"
      responses:
        '200':
          description: Texto extraído com sucesso
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OCRResponse'
              example:
                count: 1
                text: "Contrato aceito em 12 de março de 2024"
        '400':
          description: Arquivo ausente ou limites excedidos (tamanho ou páginas)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Limite excedido. O arquivo ultrapassa 2MB"
        '500':
          description: Erro interno ao processar OCR
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Erro ao processar o arquivo PDF."

  /api/v3/offload:
    post:
      summary: Disparar processamento assíncrono (offload)
      tags: [Offload]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OffloadRequest'
            example:
              tenant: "cliente-a"
              model: "gpt-4.1"
              payload:
                text: "conteúdo para processar"
      responses:
        '200':
          description: Workflow registrado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OffloadResponse'
              example:
                message: OK
        '400':
          description: Falha de autenticação ou corpo inválido
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/offloadstatus/{workflow_id}:
    get:
      summary: Consultar status de um workflow
      tags: [Offload]
      parameters:
        - name: workflow_id
          in: path
          required: true
          schema:
            type: string
          description: "ID do workflow retornado pelo Temporal"
      responses:
        '200':
          description: Status do workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OffloadStatusResponse'
              example:
                status: "RUNNING"
        '500':
          description: Erro ao consultar status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "-1"

  /api/v3/offloadcancel/{workflow_id}:
    post:
      summary: Cancelar workflow em andamento
      tags: [Offload]
      parameters:
        - name: workflow_id
          in: path
          required: true
          schema:
            type: string
          description: "ID do workflow retornado pelo Temporal"
      responses:
        '200':
          description: Cancelamento solicitado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OffloadCancelResponse'
              example:
                status: success
                message: "Workflow wf-123 canceled."
        '500':
          description: Erro ao cancelar
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "-1"

  /api/v3/insights_chat:
    get:
      summary: Listar templates de insights de chat
      tags: [Insights]
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Lista de templates disponíveis
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InsightsChatListResponse'
              example:
                data:
                  - id: "1"
                    name: "Suporte"
                    type: chat
                    cat: support
                    insights: true
                    insights_prompt: "Faça uma análise do atendimento de suporte e gere insights relevantes"
                    resume: true
                    resume_prompt: "Faça um resumo do atendimento de suporte em um parágrafo"
                    sentimental: true
                    sentimental_prompt: "Retorne umas das opções (Positivo,Neutro,Negativo) da conversa"
                    tags: true
                    tags_prompt: "Gere tags relevantes para o atendimento de suporte sempre iniciando com #"
                    m_like: true
                    m_like_prompt: "Analise se o atendimento foi satisfatório do ponto de vista do usuário. Retorne 'true' se o usuário ficou satisfeito ou 'false' se ficou insatisfeito"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

    post:
      summary: Enfileirar análise de conversa via workflow de insights de chat
      tags: [Insights]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InsightsChatCreateRequest'
            example:
              id: "session-123"
              insight_chat_id: "4f8ba8d7-090e-4a29-9e63-1f2d2f9e0c7a"
              url: "https://webhook.seusistema.com/retorno-insights"
              challenge: "token-opcional"
              m_like: 1
              data:
                conversation:
                  - from: cliente
                    text: "Olá, preciso de ajuda com minha fatura."
                  - from: atendente
                    text: "Claro, posso verificar isso para você."
      responses:
        '202':
          description: Solicitação enfileirada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InsightsChatQueuedResponse'
              example:
                status: queued
                id: "session-123"
                workflow_id: "insights-chat-automacao-session-123-abc123"
        '400':
          description: Campos obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MissingFieldsResponse'
              example:
                message: "Missing required fields"
                fields: [id, insight_chat_id, url, data]
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '404':
          description: Template não encontrado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Template not found"
        '409':
          description: Workflow já em execução para o ID informado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkflowAlreadyStartedResponse'
              example:
                message: "Workflow already in progress"
                workflow_id: "insights-chat-automacao-session-123-abc123"
                id: "session-123"
        '500':
          description: Erro ao enfileirar workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Failed to enqueue workflow"

  /api/v3/insights_chat/{insight_id}:
    get:
      summary: Buscar template específico de insights de chat
      tags: [Insights]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: insight_id
          in: path
          required: true
          schema:
            type: string
          description: ID do template salvo
      responses:
        '200':
          description: Template encontrado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InsightsChatTemplateResponse'
              example:
                data:
                  id: "4f8ba8d7-090e-4a29-9e63-1f2d2f9e0c7a"
                  name: "Comercial"
                  description: "Template de insights comerciais"
                  type: chat
                  cat: sales
                  insights: true
                  insights_prompt: "Identifique oportunidades de upsell e pontos de atrito."
                  conversation: true
                  resume: true
                  resume_prompt: "Resuma os principais pontos tratados."
                  sentimental: true
                  sentimental_prompt: "Classifique o sentimento do cliente."
                  tags: true
                  tags_prompt: "Extraia até 3 tags relevantes."
                  m_like: true
                  m_like_prompt: "Analise se o atendimento foi satisfatório."
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '404':
          description: Template não encontrado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Insight not found"

  /api/v3/chat_insights:
    post:
      summary: Gerar insights imediatos de chat (legado)
      tags: [Insights]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatInsightsRequest'
            example:
              user_instructions: "Analise a conversa e identifique as principais necessidades do cliente. Crie tags relacionadas ao atendimento ao cliente e vendas."
              history:
                - input: "Olá, preciso de ajuda com meu pedido"
                  output: "Olá! Claro, posso ajudar com seu pedido. Qual é o número do seu pedido?"
                - input: "É o pedido 12345"
                  output: "Encontrei seu pedido 12345. Ele está em processamento. Qual é sua dúvida?"
                - input: "Quando será entregue?"
                  output: "Seu pedido será entregue em até 3 dias úteis. Você receberá um código de rastreamento por email."
      responses:
        '200':
          description: Insights gerados pelo LLM
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatInsightsResponse'
              example:
                response:
                  resumo: "O cliente entrou em contato para obter informações sobre o status do pedido e recebeu prazo de entrega."
                  tags: ["#atendimento", "#pedido", "#entrega", "#suporte"]
                  sentimental:
                    sentimento: "Positivo"
        '400':
          description: Corpo inválido ou campos obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "user_instructions not found"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error

  /api/v3/customer_journey:
    post:
      summary: Gerar jornada do cliente
      tags: [Analytics e Journey]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CustomerJourneyRequest'
            example:
              date: "2024-01-01"
              platform": "whatsapp"
              workflow": "atendimento"
              history":
                - input: "Oi"
                  output: "Olá, posso ajudar."
      responses:
        '200':
          description: Jornada do cliente gerada com sucesso
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CustomerJourneyResponse'
              example:
                status: "success"
                journey:
                  score: 5
                  sentiment: "Positivo"
                  summary: "O cliente iniciou o contato para tirar dúvidas sobre o produto X e finalizou a compra com sucesso."
                  like: true
                  user_name": "João"
                  tags": ["compra", "produto_x"]
        '400':
          description: Parâmetros obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                status: "error"
                message: "Parâmetros obrigatórios: date, platform, workflow, history"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Erro interno ao gerar a jornada do cliente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                status: "error"
                message": "detalhe do erro"
  /api/v3/reports/insights:
    get:
      summary: Consultar relatórios de insights com filtros e paginação
      tags: [Insights]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: page
          in: query
          required: false
          schema:
            type: integer
            default: 1
          description: Número da página (inicia em 1)
        - name: items_per_page
          in: query
          required: false
          schema:
            type: integer
            default: 5
          description: Quantidade de itens por página (máximo 100)
        - name: order_by
          in: query
          required: false
          schema:
            type: string
            enum: [created_at, score, m_like, completed, agent_name]
            default: created_at
          description: Campo de ordenação
        - name: order_direction
          in: query
          required: false
          schema:
            type: string
            enum: [asc, desc]
            default: desc
          description: Direção da ordenação
        - name: tags
          in: query
          required: false
          schema:
            type: array
            items:
              type: string
          style: form
          explode: true
          description: Tags para filtrar (pode repetir o parâmetro para múltiplas tags)
        - name: tags_match
          in: query
          required: false
          schema:
            type: string
            enum: [all, any]
            default: all
          description: Modo de correspondência das tags (all = precisa conter todas, any = qualquer uma)
        - name: search_filter
          in: query
          required: false
          schema:
            type: string
          description: Filtro textual aplicado aos filtros indexados
        - name: agent_id
          in: query
          required: false
          schema:
            type: string
          description: Filtrar por ID do agente
        - name: date_type
          in: query
          required: false
          schema:
            type: string
            enum: [relative, absolute]
          description: Tipo de filtro de data
        - name: relative_days
          in: query
          required: false
          schema:
            type: integer
          description: Quantidade de dias para filtro relativo
        - name: start_datetime
          in: query
          required: false
          schema:
            type: string
            format: date-time
          description: Data/hora inicial para filtro absoluto (ISO 8601)
        - name: end_datetime
          in: query
          required: false
          schema:
            type: string
            format: date-time
          description: Data/hora final para filtro absoluto (ISO 8601)
        - name: download
          in: query
          required: false
          schema:
            type: boolean
            default: false
          description: Quando true inclui histórico completo para download
      responses:
        '200':
          description: Lista paginada de curadorias e metadados de filtros
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InsightsReportResponse'
              example:
                items:
                  - id: 1
                    agent_id: "uuid-do-agente"
                    curator_id: "uuid-do-curador"
                    agent_name: "Nome do Agente"
                    m_like: 1
                    completed: 1
                    insights: "Insights da conversa..."
                    created_at: "2023-12-01T10:00:00"
                    score: 4.5
                    response_time: 1200
                    interaction_count: 5
                    message_count: 10
                    workflow_name: "atendimento"
                    platform: "whatsapp"
                    initial_time: "2023-12-01T09:58:00"
                    final_time: "2023-12-01T10:02:00"
                    tags: ["#vendas", "#suporte"]
                    filters: ["filtro1", "filtro2"]
                pagination:
                  current_page: 1
                  items_per_page: 5
                  total_items: 100
                  total_pages: 20
                filters:
                  order_by: created_at
                  order_direction: desc
                  tags: []
                  tags_match: all
                  search_filter: ""
                  agent_id: null
                  date_filter:
                    date_type: null
                    relative_days: null
                    start_datetime: null
                    end_datetime: null
                    applied: false
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Erro ao recuperar insights
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InsightsReportErrorResponse'
              example:
                error: "An error occurred while retrieving insights"
                items: []
                pagination:
                  current_page: 1
                  items_per_page: 5
                  total_items: 0
                  total_pages: 0

  /api/v3/go_summarize:
    post:
      summary: Gerar resumo de atendimento (curadoria rápida)
      tags: [Insights]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GoSummarizeRequest'
            example:
              history:
                - input: "Olá, preciso de ajuda com a fatura"
                  output: "Claro, pode informar o número?"
                - input: "12345"
                  output: "Encontrei sua fatura, vencimento amanhã."
      responses:
        '200':
          description: Resumo gerado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GoSummarizeResponse'
              example:
                status: success
                resume: "Cliente solicitou fatura, atendente confirmou vencimento e próximo passo."
        '400':
          description: JSON inválido
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Invalid JSON provided"
        '500':
          description: Erro ao gerar resumo
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Erro ao processar"

  /api/v3/go_curator:
    post:
      summary: Executar curadoria de conversa
      tags: [Insights]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GoCuratorRequest'
            example:
              agent_id: "agent_123"
              workflow_name: "atendimento"
              platform: "whatsapp"
              history:
                - input: "oi"
                  output: "Olá!"
              initial_time: "2024-01-01T10:00:00"
              final_time: "2024-01-01T10:05:00"
      responses:
        '200':
          description: Curadoria executada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GoCuratorResponse'
              example:
                message: "Curadoria executada com sucesso."
        '400':
          description: Parâmetros obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Faltam parâmetros: agent_id, history, workflow_name ou platform"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Erro interno ao processar curadoria
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Erro ao processar jornada do cliente"

  /api/v3/local/create_agent_template:
    post:
      summary: Gerar template de agente a partir de instruções
      tags: [Curadoria e templates]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateTemplateRequest'
            example:
              instructions: "Crie um agente de suporte para faturamento"
      responses:
        '200':
          description: Template gerado
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
        '400':
          description: Instruções ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Faltam instruções para criar o agente"
        '500':
          description: Erro ao gerar template
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Não foi possível criar o agente. Tente novamente."

  /api/v3/local/create_curator_template:
    post:
      summary: Gerar template de curador a partir de instruções
      tags: [Curadoria e templates]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateTemplateRequest'
            example:
              instructions: "Curador para tickets de suporte nível 1"
      responses:
        '200':
          description: Template gerado
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
        '400':
          description: Instruções ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Faltam instruções para criar o curador"
        '500':
          description: Erro ao gerar template
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Erro ao gerar template do curador"

  /api/v3/ping:
    get:
      summary: Healthcheck da API
      tags: [Autenticação e sistema]
      responses:
        '200':
          description: Status OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                  timestamp:
                    type: string
                  service:
                    type: string
              example:
                status: ok
                timestamp: "2024-01-01T12:00:00"
                service: genier-api

  /api/v3/flow_sso_token:
    post:
      summary: Gerar token temporário para SSO no Flow
      tags: [Autenticação e sistema]
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Token UUID gerado
          content:
            text/plain:
              schema:
                type: string
              example: "f6c8a9f4-1234-4c2a-9e1b-2a5c3c9f2b1a"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Auth Error
        '500':
          description: Erro interno
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Internal Server Error"

  /api/v3/reverse_copilot/question:
    post:
      summary: Gerar pergunta para copilot reverso
      tags: [Reverse copilot]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReverseCopilotQuestionRequest'
            example:
              history:
                - input: "Qual status do pedido?"
                  output: "Pedido em separação."
      responses:
        '200':
          description: Pergunta formatada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReverseCopilotResponse'
        '400':
          description: Corpo inválido ou history ausente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "history not found"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Erro ao processar pergunta
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v3/reverse_copilot/answer:
    post:
      summary: Humanizar resposta para copilot reverso
      tags: [Reverse copilot]
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReverseCopilotAnswerRequest'
            example:
              history:
                - input: "Quando entrega?"
                  output: "Em 3 dias úteis."
              original_question: "Quando será entregue?"
              human_answer: "Chega em até 3 dias úteis, tudo bem?"
              voice: false
      responses:
        '200':
          description: Resposta humanizada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReverseCopilotAnswerResponse'
        '400':
          description: Campos obrigatórios ausentes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "original_question not found"
        '401':
          description: Falha de autenticação
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Erro ao processar resposta
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /api/v3/email_image/{image_name}.png:
    get:
      summary: Servir imagem base64 configurada via env
      tags: [Arquivos e recursos]
      parameters:
        - name: image_name
          in: path
          required: true
          schema:
            type: string
          description: "Nome da variável (ex.: logo_lg)"
      responses:
        '200':
          description: Imagem PNG
          content:
            image/png:
              schema:
                type: string
                format: binary
        '400':
          description: Nome inválido
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Invalid image name format"
        '404':
          description: Imagem não encontrada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Image not found"
        '500':
          description: Erro ao processar imagem
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error: "Error processing image"

  /api/v3/webchat_mm/{agent_id}:
    post:
      summary: Executar agente multimodal via WebChat
      tags: [Agentes]
      parameters:
        - name: agent_id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentMMJsonRequest'
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/AgentMMFormRequest'
      responses:
        '200':
          description: Resposta do agente multimodal
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentResponseData'
        '400':
          description: Falha de autenticação ou corpo inválido
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                message: "Auth Error"

  /api/v3/unlink/{filename}:
    get:
      summary: Remover arquivo estático
      tags: [Arquivos e recursos]
      parameters:
        - name: filename
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Arquivo removido
          content:
            text/plain:
              schema:
                type: string
        '500':
          description: Erro ao remover arquivo
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'


components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization

  schemas:
    AgentVoiceRequest:
      type: object
      required: [text, agent_id, slug]
      properties:
        text:
          type: string
          description: Texto a sintetizar
        agent_id:
          type: string
          description: ID do agente (aceita "agent_<uuid>" ou apenas "<uuid>")
        slug:
          type: string
          description: Nome do arquivo de saída (será salvo como .mp3)

    AgentVoiceResponse:
      type: object
      properties:
        result:
          type: string
        message:
          type: string
        public_url:
          type: string

    AgentRequest:
      type: object
      required: [query, history]
      properties:
        query:
          type: string
          description: Pergunta do usuário
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
        tts:
          type: boolean
          default: false
        user_prompt:
          type: string
          description: Instruções adicionais para o agente
        voice_priority:
          type: boolean
          default: false
        ask_human:
          type: boolean
          default: false

    WebchatRequest:
      type: object
      required: [query, history]
      properties:
        query:
          type: string
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
        tts:
          type: boolean
          default: false

    AgentMMJsonRequest:
      type: object
      required: [history, text]
      properties:
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
        text:
          type: string
          description: Texto a ser processado (quando não usar arquivos)
        tts:
          type: boolean
          default: false
        hashtag:
          type: boolean
          default: false
          description: Se true, remove e retorna hashtags encontradas
        ask_human:
          type: boolean
          default: false
        user_prompt:
          type: string
        voice_priority:
          type: boolean
          default: false
        session_id:
          type: string
          format: uuid

    AgentMMFormRequest:
      type: object
      required: [history]
      properties:
        history:
          type: string
          description: JSON serializado do histórico (obrigatório)
        text:
          type: string
        audio:
          type: string
          format: binary
        ocr:
          type: string
          format: binary
        files:
          type: array
          items:
            type: string
            format: binary
        tts:
          type: string
          description: Booleano em string ("true"/"false")
        hashtag:
          type: string
          description: Booleano em string ("true"/"false")
        ask_human:
          type: string
          description: Booleano em string ("true"/"false")
        user_prompt:
          type: string
        voice_priority:
          type: string
          description: Booleano em string ("true"/"false")
        session_id:
          type: string
          description: UUID opcional

    AgentResponseData:
      type: object
      properties:
        status:
          type: integer
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
        response:
          type: string
        entity:
          type: boolean
        entity_content:
          type: object
        tts_audio_mp3_encoded_base64:
          type: string
        file_encoded_base64:
          type: string
        session_id:
          type: string

    AgentListItem:
      type: object
      properties:
        name:
          type: string
        id:
          type: string

    HistoryItem:
      type: object
      properties:
        input:
          type: string
        output:
          type: string
        role:
          type: string
          description: Papel opcional no diálogo

    ErrorResponse:
      type: object
      properties:
        message:
          type: string

    TTSRequest:
      type: object
      required: [query]
      properties:
        query:
          type: string
          description: Texto a ser sintetizado
        tts_config_id:
          type: string
          description: ID da configuração TTS (opcional; usa padrão se ausente)

    TTSResponse:
      type: object
      properties:
        audio_content_base64:
          type: string
          description: Áudio MP3 em base64
        config_used:
          type: string
        provider:
          type: string
        model:
          type: string
        voice:
          type: string

    STTTranscribeRequest:
      type: object
      required: [file]
      properties:
        file:
          type: string
          format: binary
          description: Arquivo de áudio para transcrição
        data:
          type: string
          description: "JSON serializado com metadados opcionais (ex.: lang)"

    STTTranscribeResponse:
      type: object
      properties:
        source:
          type: string
        result:
          type: string

    VoiceverseRequest:
      type: object
      required: [pipeline, file]
      properties:
        pipeline:
          type: string
          description: "ID do pipeline (ex.: call_center)"
        file:
          type: string
          format: binary
          description: Arquivo de áudio a processar

    VoiceverseResponse:
      type: object
      properties:
        transcribed:
          type: object
          properties:
            response:
              type: string
        conversation:
          type: string
        resume:
          type: string
        sentimental:
          type: string

    VoiceverseListItem:
      type: object
      properties:
        pipeline_name:
          type: string
        pipeline_id:
          type: string
        steps:
          type: array
          items:
            type: string

    VoiceverseContent:
      type: object
      description: JSON do pipeline salvo em data/pipelines

    RunLLMRequest:
      type: object
      required: [prompt, payload]
      properties:
        prompt:
          type: string
          description: Prompt/instrução principal
        payload:
          type: object
          description: Dados de entrada (contexto)
        reasoning_effort:
          type: string
          description: "Esforço de raciocínio (ex.: medium)"
        verbosity:
          type: string
          description: "Nível de verbosidade da resposta"

    RunLLMResponse:
      type: object
      properties:
        output:
          type: string
        metadata:
          type: object

    GenerateRequest:
      type: object
      required: [model, query]
      properties:
        model:
          type: string
          description: "Modelo a ser usado (ex.: gpt-4.1)"
        query:
          type: string
          description: "Texto de entrada"
        session:
          type: string
          description: "Session ID opcional (UUID)"

    GenerateResponse:
      type: object
      properties:
        response:
          type: string
        session:
          type: string

    OffloadRequest:
      type: object
      required: [tenant, model]
      properties:
        tenant:
          type: string
          description: "Tenant alvo do processamento"
        model:
          type: string
          description: "Modelo a ser usado"
        payload:
          type: object
          description: "Dados adicionais a serem enviados para o workflow"

    OffloadResponse:
      type: object
      properties:
        message:
          type: string

    OffloadStatusResponse:
      type: object
      properties:
        status:
          type: string

    OffloadCancelResponse:
      type: object
      properties:
        status:
          type: string
        message:
          type: string

    OCRRequest:
      type: object
      required: [file]
      properties:
        file:
          type: string
          format: binary
          description: Arquivo PDF ou imagem para OCR
        lang:
          type: string
          description: "Código de idioma do OCR (padrão 'por' para português)"
          default: por

    OCRResponse:
      type: object
      properties:
        count:
          type: integer
          description: Número de páginas processadas (1 para imagens)
        text:
          type: string
          description: Texto extraído do arquivo

    InsightsChatTemplate:
      type: object
      additionalProperties: true
      properties:
        id:
          type: string
        name:
          type: string
        description:
          type: string
        type:
          type: string
          description: Tipo de pipeline (sempre "chat")
        cat:
          type: string
          description: Categoria do template
        insights:
          type: boolean
          description: Habilita geração de insights detalhados
        insights_prompt:
          type: string
        conversation:
          type: boolean
          description: Define se o template inclui análise de conversa completa
        resume:
          type: boolean
          description: Habilita resumo do atendimento
        resume_prompt:
          type: string
        sentimental:
          type: boolean
          description: Habilita análise de sentimento
        sentimental_prompt:
          type: string
        tags:
          type: boolean
          description: Habilita extração de tags
        tags_prompt:
          type: string
        m_like:
          type: boolean
          description: Habilita avaliação de satisfação (like/dislike)
        m_like_prompt:
          type: string

    InsightsChatListResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/InsightsChatTemplate'

    InsightsChatTemplateResponse:
      type: object
      properties:
        data:
          $ref: '#/components/schemas/InsightsChatTemplate'

    InsightsChatCreateRequest:
      type: object
      required: [id, insight_chat_id, url, data]
      properties:
        id:
          type: string
          description: "Identificador único da requisição (ex.: ID da sessão)"
        insight_chat_id:
          type: string
          description: ID do template de insights de chat a ser usado
        url:
          type: string
          format: uri
          description: URL do webhook que receberá o resultado
        challenge:
          type: string
          description: Token opcional enviado como Bearer no callback
        data:
          type: object
          description: Payload com histórico ou metadados da conversa a ser analisada
        m_like:
          type: integer
          format: int32
          description: Avaliação opcional do usuário (1 = positivo, 0 = negativo)

    InsightsChatQueuedResponse:
      type: object
      properties:
        status:
          type: string
        id:
          type: string
        workflow_id:
          type: string

    MissingFieldsResponse:
      type: object
      properties:
        message:
          type: string
        fields:
          type: array
          items:
            type: string

    WorkflowAlreadyStartedResponse:
      type: object
      properties:
        message:
          type: string
        workflow_id:
          type: string
        id:
          type: string

    ChatMessage:
      type: object
      properties:
        input:
          type: string
          description: Texto enviado pelo usuário
        output:
          type: string
          description: Resposta do bot/atendente

    ChatInsightsRequest:
      type: object
      required: [user_instructions, history]
      properties:
        user_instructions:
          type: string
          description: Instruções para orientar a análise do LLM
        history:
          type: array
          items:
            $ref: '#/components/schemas/ChatMessage'

    ChatInsightsResponse:
      type: object
      properties:
        response:
          type: object
          properties:
            resumo:
              type: string
            tags:
              type: array
              items:
                type: string
            sentimental:
              type: object
              properties:
                sentimento:
                  type: string
                  description: "Positivo, Negativo ou Neutro"

    InsightsReportItem:
      type: object
      properties:
        id:
          type: integer
        agent_id:
          type: string
        curator_id:
          type: string
        agent_name:
          type: string
        m_like:
          type: integer
          description: Avaliação do usuário (1, 0 ou null)
          nullable: true
        completed:
          type: integer
        insights:
          type: string
        created_at:
          type: string
          format: date-time
        score:
          type: number
          format: float
        response_time:
          type: number
        interaction_count:
          type: integer
        message_count:
          type: integer
        workflow_name:
          type: string
        platform:
          type: string
        initial_time:
          type: string
          format: date-time
        final_time:
          type: string
          format: date-time
        tags:
          type: array
          items:
            type: string
        filters:
          type: array
          items:
            type: string
        history:
          type: array
          items:
            type: object
          description: Incluído somente quando download=true

    InsightsReportResponse:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/InsightsReportItem'
        pagination:
          type: object
          properties:
            current_page:
              type: integer
            items_per_page:
              type: integer
            total_items:
              type: integer
            total_pages:
              type: integer
        filters:
          type: object
          properties:
            order_by:
              type: string
            order_direction:
              type: string
            tags:
              type: array
              items:
                type: string
            tags_match:
              type: string
            search_filter:
              type: string
            agent_id:
              type: string
              nullable: true
            date_filter:
              type: object
              properties:
                date_type:
                  type: string
                  nullable: true
                relative_days:
                  type: integer
                  nullable: true
                start_datetime:
                  type: string
                  format: date-time
                  nullable: true
                end_datetime:
                  type: string
                  format: date-time
                  nullable: true
                applied:
                  type: boolean

    InsightsReportErrorResponse:
      type: object
      properties:
        error:
          type: string
        items:
          type: array
          items:
            $ref: '#/components/schemas/InsightsReportItem'
        pagination:
          type: object
          properties:
            current_page:
              type: integer
            items_per_page:
              type: integer
            total_items:
              type: integer
            total_pages:
              type: integer

    CustomerJourneyRequest:
      type: object
      required: [date, platform, workflow, history]
      properties:
        date:
          type: string
          format: date
          description: Data da jornada no formato YYYY-MM-DD
        platform:
          type: string
          description: Nome da plataforma de origem
        workflow:
          type: string
          description: Nome do workflow executado
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
          description: Histórico de interações da conversa

    CustomerJourneyResponse:
      type: object
      properties:
        status:
          type: string
          enum: [success, error]
        journey:
          type: object
          properties:
            score:
              type: integer
              description: Pontuação da jornada (0-5)
            sentiment:
              type: string
              description: Sentimento geral (Positivo, Neutro, Negativo)
            summary:
              type: string
              description: Resumo da jornada do cliente
            like:
              type: boolean
              description: Indica se o cliente ficou satisfeito
            user_name:
              type: string
              description: Nome do usuário
            tags:
              type: array
              items:
                type: string
              description: Lista de tags relevantes
        message:
          type: string
          description: Mensagem de erro em caso de falha

    GoSummarizeRequest:
      type: object
      properties:
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
          description: Histórico de atendimento a ser resumido
      additionalProperties: true

    GoSummarizeResponse:
      type: object
      properties:
        status:
          type: string
        resume:
          type: string
          description: Resumo gerado
      additionalProperties: true

    GoCuratorRequest:
      type: object
      required: [agent_id, history, workflow_name, platform, initial_time, final_time]
      properties:
        agent_id:
          type: string
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
        workflow_name:
          type: string
        platform:
          type: string
        initial_time:
          type: string
        final_time:
          type: string

    GoCuratorResponse:
      type: object
      properties:
        message:
          type: string

    CreateTemplateRequest:
      type: object
      required: [instructions]
      properties:
        instructions:
          type: string
          description: Instruções em linguagem natural para gerar o template

    ReverseCopilotQuestionRequest:
      type: object
      required: [history]
      properties:
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'

    ReverseCopilotResponse:
      type: object
      properties:
        response:
          type: string
      additionalProperties: true

    ReverseCopilotAnswerRequest:
      type: object
      required: [history, original_question, human_answer]
      properties:
        history:
          type: array
          items:
            $ref: '#/components/schemas/HistoryItem'
        original_question:
          type: string
        human_answer:
          type: string
        voice:
          type: boolean
          default: false

    ReverseCopilotAnswerResponse:
      type: object
      properties:
        response:
          type: string
        tts_audio_mp3_encoded_base64:
          type: string
          description: Áudio MP3 em base64 ou "NA" se indisponível
      additionalProperties: true
