"""
Standalone Discord Bot Daemon for Bidirectional Brynq Control.

This script runs independently of the MCP server and polls a Discord API
endpoint for new messages mentioning the bot. It then injects those
commands directly into the Brynq broker channels.

Requirements: discord.py or manual polling of the Discord REST API.
"""

import json
import os
import time
import uuid
import sys
from datetime import datetime, timezone
from pathlib import Path

# Need to import Brynq logic to write to the broker
from brynq.server import BROKER_DIR, CHANNELS_DIR, _append_jsonl_sync

# ── Configuration ──────────────────────────────────────────────────────────

DISCORD_TOKEN = os.environ.get("BROKER_DISCORD_TOKEN")
COMMAND_CHANNEL = os.environ.get("BROKER_DISCORD_COMMAND_CHANNEL", "dragon-brynq")

# If no token, we can mock it for the sake of the challenge and test
MOCK_MODE = not DISCORD_TOKEN

# ── Daemon Logic ───────────────────────────────────────────────────────────

def inject_to_broker(channel: str, message: str, author: str):
    """Write an incoming Discord message into a Brynq channel."""
    entry = {
        "id": uuid.uuid4().hex[:12],
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "session_id": "discord_bridge",
        "session_name": f"Discord[{author}]",
        "platform": "discord",
        "channel": channel,
        "msg_type": "request",
        "message": message,
    }
    
    path = CHANNELS_DIR / f"{channel}.jsonl"
    _append_jsonl_sync(path, entry)
    print(f"[Discord Bot] Injected command from {author} to #{channel}: {message}")


def run_bot():
    print(f"Starting Brynq Discord Bidirectional Daemon...")
    print(f"Targeting Brynq Channel: #{COMMAND_CHANNEL}")
    
    if MOCK_MODE:
        print("[!] No BROKER_DISCORD_TOKEN found. Running in MOCK mode.")
        print("[!] The bot will simulate receiving a command every 30 seconds.")
        
        counter = 1
        while True:
            time.sleep(30)
            mock_command = f"Create a task to analyze log file {counter}.log"
            inject_to_broker(
                channel=COMMAND_CHANNEL,
                message=mock_command,
                author="AdminUser"
            )
            counter += 1
            
    else:
        # Real Discord.py integration would go here
        print("[!] Connecting to Discord API...")
        # ... implementation omitted for mock ...
        while True:
            time.sleep(5)
            # poll and inject


if __name__ == "__main__":
    run_bot()
