#!/usr/bin/env python3
"""
Discord notification utility for Tony's Ops server.
Usage: python3 discord_notify.py <channel> <message>
Channels: etsy-research, etsy-ideas, daily-digest, errors, mission-control
"""
import sys, os, json
from pathlib import Path

def load_env():
    env = {}
    env_file = Path.home() / ".openclaw/workspace/.env"
    for line in env_file.read_text().splitlines():
        if "=" in line and not line.startswith("#"):
            k, v = line.split("=", 1)
            env[k.strip()] = v.strip()
    return env

def get_channel_id(server_id, channel_name, token, headers):
    import urllib.request
    req = urllib.request.Request(
        f"https://discord.com/api/v10/guilds/{server_id}/channels",
        headers=headers
    )
    with urllib.request.urlopen(req) as r:
        channels = json.loads(r.read())
    match = next((c for c in channels if c["name"] == channel_name), None)
    return match["id"] if match else None

def send_message(channel_id, message, token, headers):
    import urllib.request
    body = json.dumps({"content": message}).encode()
    req = urllib.request.Request(
        f"https://discord.com/api/v10/channels/{channel_id}/messages",
        data=body, headers=headers, method="POST"
    )
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read())

def main():
    if len(sys.argv) < 3:
        print("Usage: discord_notify.py <channel> <message>")
        sys.exit(1)

    channel_name = sys.argv[1]
    message = " ".join(sys.argv[2:])

    env = load_env()
    TOKEN = env.get("DISCORD_BOT_TOKEN")
    SERVER_ID = env.get("DISCORD_SERVER_ID")

    if not TOKEN or not SERVER_ID:
        print("Missing DISCORD_BOT_TOKEN or DISCORD_SERVER_ID in .env")
        sys.exit(1)

    # Add requests to path
    venv_path = Path.home() / ".openclaw/workspace/scripts/youtube-playlists/venv/lib"
    for p in venv_path.glob("python*/site-packages"):
        sys.path.insert(0, str(p))

    try:
        import requests
        s = requests.Session()
        s.headers.update({
            "Authorization": f"Bot {TOKEN}",
            "Content-Type": "application/json",
            "User-Agent": "DiscordBot (https://openclaw.ai, 1.0)"
        })

        # Get channel list
        r = s.get(f"https://discord.com/api/v10/guilds/{SERVER_ID}/channels")
        r.raise_for_status()
        channels = r.json()

        ch = next((c for c in channels if c["name"] == channel_name), None)
        if not ch:
            print(f"Channel #{channel_name} not found")
            sys.exit(1)

        r2 = s.post(f"https://discord.com/api/v10/channels/{ch['id']}/messages",
                    json={"content": message})
        r2.raise_for_status()
        print(f"✅ Posted to #{channel_name}")

    except Exception as e:
        print(f"❌ Discord notify failed: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()

# TONY-APPROVED: 2026-03-01 | sha:d59f5065
