# __init__.py formerly known as scheduler.py

import os
import yaml
import asyncio
import random
from ai import get_ai_response
from . import simple, probabilistic, inactivity
from logger import setup_logger
logger = setup_logger("scheduler")

def load_settings():
    base_dir = os.path.dirname(os.path.dirname(__file__))  # go up from /scheduler/
    settings_path = os.path.join(base_dir, "settings.yml")
    with open(settings_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)

async def start_scheduler(bot):
    settings = load_settings()
    scheduler_settings = settings.get("scheduler", {})

    # Override channel_id with environment variable if set
    channel_id_env = os.getenv("CHANNEL_ID")
    if channel_id_env:
        scheduler_settings["channel_id"] = int(channel_id_env)

    if not scheduler_settings.get("enabled", False):
        #print("🛑 Scheduler disabled in config.")
        logger.info("🛑 Scheduler disabled in config.")
        return

    mode = scheduler_settings.get("mode", "simple").lower()
    #print(f"🕒 Delta Scheduler started in {mode.upper()} mode.")
    logger.info(f"🕒 Delta Scheduler started in {mode.upper()} mode.")

    if mode == "simple":
        await simple.run(bot, scheduler_settings, settings)

    elif mode == "probabilistic":
        # Setup and loop
        probabilistic.setup(scheduler_settings["probabilistic"])

        interval = scheduler_settings.get("interval_minutes", 5)
        use_ai = scheduler_settings.get("use_ai", True)
        channel = bot.get_channel(scheduler_settings["channel_id"])

        await bot.wait_until_ready()

        while not bot.is_closed():
            if probabilistic.should_post(scheduler_settings["probabilistic"]):
                if use_ai:
                    prompt = "Post a short chaotic or motivational message in the voice of Delta, the RGB catgirl."
                    message = get_ai_response(prompt)
                else:
                    message = random.choice(scheduler_settings.get("messages", ["Hello from Delta."]))

                await channel.send(message)
                #print(f"📤 Scheduled message sent to #{channel.name}: {message}")
                logger.info(f"📤 Scheduled message sent to #{channel.name}: {message}")

                probabilistic.on_post(scheduler_settings["probabilistic"])

            await asyncio.sleep(interval * 60)

    elif mode == "inactivity":
        await inactivity.run(bot, scheduler_settings, settings)

    else:
        #print(f"❓ Unknown scheduler mode: {mode}")
        logger.info(f"❓ Unknown scheduler mode: {mode}")
