{"openapi":"3.1.0","info":{"title":"iFriend Multi-Platform Bot","version":"0.1.0"},"paths":{"/api/analytics/overview":{"get":{"tags":["analytics"],"summary":"Get Overview","description":"KPIs resumidos: total processos, sessões, custo estimado, trend.","operationId":"get_overview_api_analytics_overview_get","parameters":[{"name":"start_date","in":"query","required":false,"schema":{"type":"string","format":"date","title":"Start Date"}},{"name":"end_date","in":"query","required":false,"schema":{"type":"string","format":"date","title":"End Date"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OverviewResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/analytics/processes":{"get":{"tags":["analytics"],"summary":"Get Processes","description":"Breakdown por processo P1-P8 com contagem, custo e trend.","operationId":"get_processes_api_analytics_processes_get","parameters":[{"name":"start_date","in":"query","required":false,"schema":{"type":"string","format":"date","title":"Start Date"}},{"name":"end_date","in":"query","required":false,"schema":{"type":"string","format":"date","title":"End Date"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProcessesResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/analytics/sessions":{"get":{"tags":["analytics"],"summary":"Get Sessions","description":"Métricas de sessão: total, únicos, por plataforma, trend.","operationId":"get_sessions_api_analytics_sessions_get","parameters":[{"name":"start_date","in":"query","required":false,"schema":{"type":"string","format":"date","title":"Start Date"}},{"name":"end_date","in":"query","required":false,"schema":{"type":"string","format":"date","title":"End Date"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SessionsResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/analytics/billing":{"get":{"tags":["analytics"],"summary":"Get Billing","description":"Relatório de cobrança mensal: processos × preço unitário.","operationId":"get_billing_api_analytics_billing_get","parameters":[{"name":"month","in":"query","required":false,"schema":{"type":"integer","maximum":12,"minimum":1,"title":"Month"}},{"name":"year","in":"query","required":false,"schema":{"type":"integer","maximum":2100,"minimum":2024,"title":"Year"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BillingResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/analytics/billing/export":{"get":{"tags":["analytics"],"summary":"Export Billing Csv","description":"Exporta relatório de cobrança como CSV.","operationId":"export_billing_csv_api_analytics_billing_export_get","parameters":[{"name":"month","in":"query","required":false,"schema":{"type":"integer","maximum":12,"minimum":1,"title":"Month"}},{"name":"year","in":"query","required":false,"schema":{"type":"integer","maximum":2100,"minimum":2024,"title":"Year"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/.well-known/agent-card.json":{"get":{"summary":"Agent Card","description":"Agent Card público para descoberta A2A.","operationId":"agent_card__well_known_agent_card_json_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/webhook/{path}":{"post":{"summary":"Unified Webhook","description":"Webhook unificado que roteia para o adapter correto.\n\nExemplos de paths:\n- /webhook/slack/events -> SlackAdapter\n- /webhook/whatsapp/webhook -> WhatsAppAdapter\n- /webhook/telegram/webhook -> TelegramAdapter","operationId":"unified_webhook_webhook__path__post","parameters":[{"name":"path","in":"path","required":true,"schema":{"type":"string","title":"Path"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"get":{"summary":"Unified Webhook","description":"Webhook unificado que roteia para o adapter correto.\n\nExemplos de paths:\n- /webhook/slack/events -> SlackAdapter\n- /webhook/whatsapp/webhook -> WhatsAppAdapter\n- /webhook/telegram/webhook -> TelegramAdapter","operationId":"unified_webhook_webhook__path__get","parameters":[{"name":"path","in":"path","required":true,"schema":{"type":"string","title":"Path"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/":{"get":{"summary":"Root","description":"Health check e informações","operationId":"root__get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/health":{"get":{"summary":"Health","description":"Endpoint de health check","operationId":"health_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/proposal/send-email":{"post":{"summary":"Send Proposal Email","description":"Envia o PDF do orçamento por email.\n\nEndpoint dedicado (fora do loop do agente): o frontend gera o PDF no\nnavegador (jsPDF), converte para base64 e chama esta rota diretamente,\nsem passar pelo LLM — ação mecânica, não precisa de raciocínio do agente.","operationId":"send_proposal_email_proposal_send_email_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendProposalEmailRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/demo/sse-chat":{"get":{"summary":"Demo Sse Chat","description":"Serve o demo HTML do SSE Chat.\n\nAcesse em: http://localhost:8080/demo/sse-chat","operationId":"demo_sse_chat_demo_sse_chat_get","responses":{"200":{"description":"Successful Response","content":{"text/html":{"schema":{"type":"string"}}}}}}},"/startup":{"get":{"summary":"Startup Check","description":"Startup probe para Cloud Run - indica que o container está pronto","operationId":"startup_check_startup_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/_ah/start":{"get":{"summary":"Startup Check","description":"Startup probe para Cloud Run - indica que o container está pronto","operationId":"startup_check__ah_start_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/webchat/message":{"post":{"summary":"Webchat Message","description":"Endpoint síncrono para WebChat widget.\n\nDiferente dos outros webhooks assíncronos, este endpoint retorna\na resposta do agente diretamente no response HTTP.\n\nRequest JSON:\n{\n  \"user_id\": \"user123\",\n  \"session_id\": \"session456\",  // Opcional\n  \"message\": \"Olá!\",\n  \"metadata\": {                // Opcional\n    \"page_url\": \"https://...\",\n    \"user_name\": \"João\",\n    ...\n  }\n}\n\nResponse JSON:\n{\n  \"response\": \"Olá! Como posso ajudar?\",\n  \"session_id\": \"session456\",\n  \"metadata\": {...}\n}","operationId":"webchat_message_webchat_message_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/sse/chat":{"post":{"summary":"Sse Chat Start","description":"Inicia conversa SSE (Server-Sent Events).\n\nRequest JSON:\n{\n  \"user_id\": \"user123\",\n  \"session_id\": \"session456\",  // Opcional\n  \"message\": \"Olá!\",\n  \"jwt_token\": \"eyJ...\",       // Opcional (JWT para autenticação)\n  \"metadata\": {...}             // Opcional\n}\n\nAutenticação JWT (múltiplas formas):\n- Header: Authorization: Bearer <token>\n- Body: jwt_token field\n- Cookie: jwt_token=<token>\n\nResponse JSON:\n{\n  \"stream_id\": \"sse_abc123...\",\n  \"session_id\": \"session456\"\n}\n\nSe JWT fornecido, retorna cookie httpOnly para uso no EventSource.\n\nEm seguida, conecte via EventSource:\n  GET /sse/stream/{stream_id}","operationId":"sse_chat_start_sse_chat_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/sse/stream/{stream_id}":{"get":{"summary":"Sse Stream","description":"Stream de eventos SSE.\n\nConecte via EventSource:\n  const eventSource = new EventSource('/sse/stream/{stream_id}');\n\nAutenticação (opcional):\n- Cookie: jwt_token=<token>\n- Query param: ?token=<token>\n\nEventos emitidos:\n- stream_start: Início do processamento\n- tool_call_start: Ferramenta sendo executada\n- tool_call_complete: Ferramenta concluída\n- text_chunk: Chunk de texto (streaming)\n- stream_complete: Processamento concluído\n- error: Erro durante processamento\n- keepalive: Keep-alive (a cada 30s)","operationId":"sse_stream_sse_stream__stream_id__get","parameters":[{"name":"stream_id","in":"path","required":true,"schema":{"type":"string","title":"Stream Id"}},{"name":"Last-Event-ID","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Last-Event-Id"}},{"name":"token","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"JWT token (alternativa ao cookie)","title":"Token"},"description":"JWT token (alternativa ao cookie)"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/sse/health":{"get":{"summary":"Sse Health","description":"Health check do SSE adapter","operationId":"sse_health_sse_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/whatsapp/link":{"post":{"summary":"Whatsapp Link Jwt","description":"Vincula JWT token a um número de WhatsApp.\n\nFluxo:\n1. Usuário se autentica no frontend (obtém JWT)\n2. Frontend chama este endpoint com JWT e telefone\n3. Backend armazena vinculação no Redis (TTL 30 dias)\n4. Quando usuário envia mensagem pelo WhatsApp, adapter faz lookup\n\nRequest JSON:\n{\n  \"phone\": \"+5511999999999\",\n  \"jwt_token\": \"eyJhbGciOi...\",  // Ou via header Authorization: Bearer <token>\n  \"ttl_days\": 30                  // Opcional, padrão: 30 dias\n}\n\nResponse JSON:\n{\n  \"success\": true,\n  \"phone\": \"+5511999999999\",\n  \"ttl_seconds\": 2592000,\n  \"expires_at\": \"2026-03-15T10:30:00Z\"\n}","operationId":"whatsapp_link_jwt_whatsapp_link_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/slack/auth":{"post":{"summary":"Slack Auth Command","description":"Endpoint para comando /ifriend-auth do Slack.\n\nUsuário executa no Slack:\n  /ifriend-auth eyJhbGciOi...\n\nSlack envia POST para este endpoint com:\n{\n  \"user_id\": \"U12345678\",\n  \"text\": \"eyJhbGciOi...\",\n  \"command\": \"/ifriend-auth\",\n  ...\n}\n\nBackend valida JWT e armazena vinculação.\n\nResponse (ephemeral message para o usuário):\n{\n  \"response_type\": \"ephemeral\",\n  \"text\": \"✅ Autenticado com sucesso!\"\n}","operationId":"slack_auth_command_slack_auth_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}}},"components":{"schemas":{"BillingLineItem":{"properties":{"process_id":{"type":"string","title":"Process Id"},"process_name":{"type":"string","title":"Process Name"},"display_name":{"type":"string","title":"Display Name"},"quantity":{"type":"integer","title":"Quantity"},"unit_price_usd":{"type":"number","title":"Unit Price Usd"},"unit_price_brl":{"type":"number","title":"Unit Price Brl"},"subtotal_usd":{"type":"number","title":"Subtotal Usd"},"subtotal_brl":{"type":"number","title":"Subtotal Brl"}},"type":"object","required":["process_id","process_name","display_name","quantity","unit_price_usd","unit_price_brl","subtotal_usd","subtotal_brl"],"title":"BillingLineItem"},"BillingResponse":{"properties":{"month":{"type":"integer","title":"Month"},"year":{"type":"integer","title":"Year"},"tenant_id":{"type":"string","title":"Tenant Id"},"tenant_type":{"type":"string","title":"Tenant Type"},"line_items":{"items":{"$ref":"#/components/schemas/BillingLineItem"},"type":"array","title":"Line Items"},"total_usd":{"type":"number","title":"Total Usd"},"total_brl":{"type":"number","title":"Total Brl"},"usd_brl_rate":{"type":"number","title":"Usd Brl Rate"},"generated_at":{"type":"string","title":"Generated At"}},"type":"object","required":["month","year","tenant_id","tenant_type","line_items","total_usd","total_brl","usd_brl_rate","generated_at"],"title":"BillingResponse"},"DailyPoint":{"properties":{"date":{"type":"string","title":"Date"},"count":{"type":"integer","title":"Count"}},"type":"object","required":["date","count"],"title":"DailyPoint"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"KPI":{"properties":{"label":{"type":"string","title":"Label"},"value":{"type":"number","title":"Value"},"previous_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Previous Value"},"change_pct":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Change Pct"}},"type":"object","required":["label","value"],"title":"KPI"},"OverviewResponse":{"properties":{"total_processes":{"type":"integer","title":"Total Processes"},"total_sessions":{"type":"integer","title":"Total Sessions"},"estimated_cost_usd":{"type":"number","title":"Estimated Cost Usd"},"estimated_cost_brl":{"type":"number","title":"Estimated Cost Brl"},"top_process":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Top Process"},"kpis":{"items":{"$ref":"#/components/schemas/KPI"},"type":"array","title":"Kpis"},"daily_trend":{"items":{"$ref":"#/components/schemas/DailyPoint"},"type":"array","title":"Daily Trend"}},"type":"object","required":["total_processes","total_sessions","estimated_cost_usd","estimated_cost_brl"],"title":"OverviewResponse"},"PlatformBreakdown":{"properties":{"platform":{"type":"string","title":"Platform"},"count":{"type":"integer","title":"Count"},"pct":{"type":"number","title":"Pct"}},"type":"object","required":["platform","count","pct"],"title":"PlatformBreakdown"},"ProcessMetric":{"properties":{"process_id":{"type":"string","title":"Process Id"},"process_name":{"type":"string","title":"Process Name"},"display_name":{"type":"string","title":"Display Name"},"count":{"type":"integer","title":"Count"},"pct_of_total":{"type":"number","title":"Pct Of Total"},"cost_usd":{"type":"number","title":"Cost Usd"},"cost_brl":{"type":"number","title":"Cost Brl"}},"type":"object","required":["process_id","process_name","display_name","count","pct_of_total","cost_usd","cost_brl"],"title":"ProcessMetric"},"ProcessTrendPoint":{"properties":{"date":{"type":"string","title":"Date"},"process_id":{"type":"string","title":"Process Id"},"count":{"type":"integer","title":"Count"}},"type":"object","required":["date","process_id","count"],"title":"ProcessTrendPoint"},"ProcessesResponse":{"properties":{"processes":{"items":{"$ref":"#/components/schemas/ProcessMetric"},"type":"array","title":"Processes"},"total":{"type":"integer","title":"Total"},"trend":{"items":{"$ref":"#/components/schemas/ProcessTrendPoint"},"type":"array","title":"Trend"}},"type":"object","required":["processes","total"],"title":"ProcessesResponse"},"SendProposalEmailRequest":{"properties":{"email":{"type":"string","title":"Email"},"pdf_base64":{"type":"string","title":"Pdf Base64"},"filename":{"type":"string","title":"Filename"},"assunto":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Assunto"},"mensagem":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Mensagem"}},"type":"object","required":["email","pdf_base64","filename"],"title":"SendProposalEmailRequest"},"SessionsResponse":{"properties":{"total_sessions":{"type":"integer","title":"Total Sessions"},"unique_users":{"type":"integer","title":"Unique Users"},"platforms":{"items":{"$ref":"#/components/schemas/PlatformBreakdown"},"type":"array","title":"Platforms"},"daily_trend":{"items":{"$ref":"#/components/schemas/DailyPoint"},"type":"array","title":"Daily Trend"}},"type":"object","required":["total_sessions","unique_users","platforms"],"title":"SessionsResponse"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"},"input":{"title":"Input"},"ctx":{"type":"object","title":"Context"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}