import os
import threading

import discord
from discord.ext import tasks

_bot_thread = None

TOKEN = os.getenv("DISCORD_TOKEN")
CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID", "0"))
PING_INTERVAL_MINUTES = int(os.getenv("PING_INTERVAL_MINUTES", "10"))

intents = discord.Intents.none()
client = discord.Client(intents=intents)


@tasks.loop(minutes=PING_INTERVAL_MINUTES)
async def send_ping():
    channel = client.get_channel(CHANNEL_ID)
    if channel is None:
        channel = await client.fetch_channel(CHANNEL_ID)
    await channel.send("ping")


@send_ping.before_loop
async def before_send_ping():
    await client.wait_until_ready()


@client.event
async def on_ready():
    if not send_ping.is_running():
        send_ping.start()
    print(f"Connected as {client.user} and ping task started.")


def run_bot():
    if not TOKEN:
        raise RuntimeError("DISCORD_TOKEN is not set.")
    if CHANNEL_ID <= 0:
        raise RuntimeError("DISCORD_CHANNEL_ID is not set or invalid.")
    client.run(TOKEN)


def start_bot():
    global _bot_thread
    if _bot_thread and _bot_thread.is_alive():
        return

    _bot_thread = threading.Thread(target=run_bot, daemon=True)
    _bot_thread.start()


if __name__ == "__main__":
    run_bot()
