import time
import os
from logger import setup_logger
from ai import get_ai_response
from user_profiles import load_user_profile
from context import fetch_recent_context, format_context

logger = setup_logger("autochat")

# Cooldown
AUTOREPLY_ENABLED = os.getenv("AUTOREPLY_ENABLED", "false").lower() == "true"
AUTOREPLY_COOLDOWN = int(os.getenv("AUTOREPLY_COOLDOWN", 60))
_last_reply_time = 0

def should_auto_reply():
    global _last_reply_time
    if not AUTOREPLY_ENABLED:
        return False

    now = time.time()
    if now - _last_reply_time >= AUTOREPLY_COOLDOWN:
        return True
    else:
        logger.info(f"🛑 Skipped passive reply due to cooldown. {round(AUTOREPLY_COOLDOWN - (now - _last_reply_time))}s left.")
        return False

def update_reply_timer():
    global _last_reply_time
    _last_reply_time = time.time()

async def generate_auto_reply(message, bot):
    context_msgs = await fetch_recent_context(message.channel)
    formatted_context = format_context(context_msgs)

    profile = load_user_profile(message.author)

    soft_prompt = (
    "You must obey these rules strictly. Do not respond unless it is clearly your turn to speak."    
    "Do NOT reply if:\n"
    "- No one is talking to you\n"
    "- Your name isn’t mentioned\n"
    "- The message has nothing to do with you\n"
    "- You already responded recently\n"
    "- The conversation is between other users and you’re not involved\n"
    "- There’s nothing interesting or chaotic to add\n\n"
    "Silence is often more powerful than speaking. Only break it if you're sure it's your moment."
)


    logger.info(f"🤖 Considering passive reply (author: {message.author.display_name})")
    logger.info(f"📚 Retrieved {len(context_msgs)} messages for passive context")

    async with message.channel.typing():
        reply = get_ai_response(soft_prompt, context=formatted_context, user_profile=profile)
        return reply.strip() if reply else None
