#!/usr/bin/env python3
"""Post l'embed du wrapper Overmind Bridge sur Discord."""
import os
import json
import urllib.request
import urllib.error

# Récupère le token depuis .env
env_path = r"C:\Users\Deamon\Desktop\Backup\Serveur MCP\discord_llm\.env"
TOKEN_PREFIX = "DISCORD_BOT_TOKEN"
token = None
with open(env_path, 'r', encoding='utf-8') as f:
    for line in f:
        if line.startswith(TOKEN_PREFIX + "="):
            token = line.split('=', 1)[1].strip()
            break
if not token:
    raise SystemExit("Token non trouve dans .env")

CHANNEL_ID = "1491078210279182500"

embed = {
    "title": "🌉 Overmind Bridge — Couche RPC unifiée",
    "description": (
        "Couche **JSON-RPC 2.0** stable au-dessus du serveur MCP Overmind.\n"
        "Transforme n'importe quel client HTTP (curl, Discord, SMS, autre agent) "
        "en orchestrateur multi-agents avec **15 methodes RPC**, session store, "
        "circuit breaker, retry, et webhook adapter prets a l'emploi.\n\n"
        "Paquetage prod : `import { ... } from 'overmind-mcp/bridge'`"
    ),
    "color": 0x5865F2,
    "fields": [
        {
            "name": "⚡ Demarrage rapide",
            "value": (
                "```\n"
                "POST /rpc\n"
                "Content-Type: application/json\n\n"
                "{\n"
                '  "jsonrpc": "2.0",\n'
                '  "id": 1,\n'
                '  "method": "agent.run",\n'
                '  "params": {\n'
                '    "agentName": "sniperbot_analyst",\n'
                '    "runner": "hermes",\n'
                '    "prompt": "...",\n'
                '    "externalKey": "+1418..."\n'
                "  }\n"
                "}\n"
                "```"
            ),
            "inline": False
        },
        {
            "name": "📚 15 methodes RPC (5 categories)",
            "value": (
                "▸ **Health** : `health.ping`\n"
                "▸ **Agent** : `agent.run` · `agent.a2a` · `agent.status` · `agent.list` · `agent.kill`\n"
                "▸ **MessageLog** : `message.history` · `message.get` · `message.replay` · `message.stats`\n"
                "▸ **Session** : `session.get` · `session.list` · `session.delete` · `session.stats`\n"
                "▸ **Webhook** : `webhook.sms` (voipms · twilio · discord · generic)"
            ),
            "inline": False
        },
        {
            "name": "🛡️ Features production",
            "value": (
                "✅ Circuit breaker (5 echecs → open 30s)\n"
                "✅ Triple timeout (connect + body + per-chunk)\n"
                "✅ Retry auto sur ETIMEDOUT/EBODYREAD/ECONNRESET\n"
                "✅ SessionStore multi-tenant (phone, userId, channelId)\n"
                "✅ DirectiveParser (auto-update SESSION_ID: reponse)\n"
                "✅ AgentRegistry + mutex (1 run par agent)\n"
                "✅ MessageLog Postgres (optionnel)\n"
                "✅ Path traversal bloque\n"
                "✅ JSON-RPC 2.0 strict (batch + error codes)"
            ),
            "inline": False
        },
        {
            "name": "🏗️ Architecture (3 couches)",
            "value": (
                "```\n"
                "Client → BridgeProxy\n"
                "            ↓\n"
                "        OverBridgeService (session + types)\n"
                "            ↓\n"
                "        OverBridgeServer (HTTP + /rpc + /webhook)\n"
                "            ↓\n"
                "        Overmind MCP :3099 (run_agent)\n"
                "```"
            ),
            "inline": False
        },
        {
            "name": "📊 Codes d'erreur (JSON-RPC 2.0)",
            "value": (
                "▸ `-32700` PARSE_ERROR (JSON malforme)\n"
                "▸ `-32600` INVALID_REQUEST\n"
                "▸ `-32601` METHOD_NOT_FOUND\n"
                "▸ `-32602` INVALID_PARAMS\n"
                "▸ `-32603` INTERNAL_ERROR\n"
                "▸ `-32003` FEATURE_DISABLED (ex: MessageLog off)\n"
                "▸ `-32004` NOT_FOUND (ex: UUID inconnu)"
            ),
            "inline": False
        },
        {
            "name": "🔌 Endpoints HTTP",
            "value": (
                "▸ `POST /rpc` — JSON-RPC 2.0 principal\n"
                "▸ `GET  /health` — Liveness probe (K8s/Docker)\n"
                "▸ `POST /webhook/:provider` — voipms/twilio/discord/generic\n"
                "▸ `GET  /f/:filename` — Static files (path traversal bloque)"
            ),
            "inline": False
        },
        {
            "name": "🚀 Clients deja migres",
            "value": (
                "✅ **discord_llm v5.0** — 100% aligne sur le wrapper, expose `/rpc` + 11 methodes testees sur sniperbot_analyst\n"
                "🔄 **bt-sms** — migration prevue (copy-paste du pattern discord_llm)"
            ),
            "inline": False
        },
        {
            "name": "🧪 Test live (sniperbot_analyst)",
            "value": (
                "```bash\n"
                "# 1. Run agent avec session multi-tenant\n"
                "curl -X POST http://127.0.0.1:3001/rpc -d '...agent.run...'\n"
                "# 2. A2A loopback\n"
                "curl -X POST http://127.0.0.1:3001/rpc -d '...agent.a2a...'\n"
                "# 3. Webhook VoIP.ms → auto-dispatch\n"
                "curl -X POST http://127.0.0.1:3001/rpc -d '...webhook.sms...'\n"
                "```\n"
                "Tous testes ✅ sur discord_llm v5.0"
            ),
            "inline": False
        }
    ],
    "footer": {
        "text": "Overmind Bridge v5.0 · discord_llm v5.0 · sniperbot_analyst sur runner=hermes (glm-5.1)"
    }
}

payload = {"embeds": [embed]}
data = json.dumps(payload).encode('utf-8')

req = urllib.request.Request(
    f"https://discord.com/api/v10/channels/{CHANNEL_ID}/messages",
    data=data,
    method='POST',
    headers={
        'Authorization': f'Bot {token}',
        'Content-Type': 'application/json',
        'User-Agent': 'DiscordBot (overmind-bridge, 5.0.0)',
    }
)

try:
    with urllib.request.urlopen(req, timeout=30) as resp:
        body = resp.read().decode('utf-8')
        result = json.loads(body)
        print(f"OK: embed poste")
        print(f"  message_id = {result.get('id')}")
        print(f"  channel_id = {result.get('channel_id')}")
        guild = result.get('guild_id')
        if guild:
            print(f"  url        = https://discord.com/channels/{guild}/{result.get('channel_id')}/{result.get('id')}")
        else:
            print(f"  url        = https://discord.com/channels/@me/{result.get('channel_id')}/{result.get('id')}")
except urllib.error.HTTPError as e:
    print(f"ERREUR HTTP {e.code}: {e.reason}")
    try:
        print(f"  body: {e.read().decode('utf-8')[:1000]}")
    except: pass
except Exception as e:
    print(f"ERREUR: {e}")
