import json
import db
import config
import redis

_redis_client = None

def _get_redis():
    global _redis_client
    if _redis_client is None:
        try:
            _redis_client = redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT, db=0, decode_responses=True)
        except Exception as e:
            print(f"FAILED TO CONNECT TO REDIS IN HOOKS: {e}")
    return _redis_client

def on_order_created(order_id: int):
    """
    Hook triggered asynchronously when a new order is placed.
    """
    print(f"EVENT: Order {order_id} created.")

def on_order_status_changed(order_id: int, status: str, order_data: dict, send_notification: bool):
    """
    Hook triggered asynchronously when the admin changes the order status.
    """
    print(f"EVENT: Order {order_id} status changed to {status}. Notify user: {send_notification}")
    
    if send_notification:
        user_email = order_data.get('email')
        first_name = order_data.get('first_name')
        user_id = order_data.get('user_id')
        
        lang = "en"
        if user_id:
            user_info = db.execute_query("SELECT preferred_language FROM users WHERE id = %s", (user_id,))
            if user_info and user_info[0].get('preferred_language'):
                lang = user_info[0]['preferred_language']
        
        import notifications
        notifications.notify_status_change(user_email, order_id, status, first_name, lang)

def on_message_received(order_id: int, user_id: int, message: str, image_url: str = None):
    """
    Hook triggered when a client sends a message to an order chat.
    Duplicates message to Redis for Telegram notification.
    """
    print(f"EVENT: New message for Order {order_id} from User {user_id}: {str(message)[:20]}...")
    
    r = _get_redis()
    if r and config.TELEGRAM_CHAT_ID:
        try:
            # Fetch user name for better notification
            user_res = db.execute_query("SELECT first_name, last_name FROM users WHERE id = %s", (user_id,))
            name = f"{user_res[0].get('first_name', 'User')} {user_res[0].get('last_name', '')}".strip() if user_res else "Client"
            
            msg_text = message if message else "Image uploaded"
            full_msg = f"💬 <b>Новое сообщение</b>\nЗаказ: #{order_id}\nОт: <b>{name}</b>\n\n{msg_text}"
            
            if image_url:
                full_msg += f"\n\n🖼️ <b>Вложение:</b> {config.FRONTEND_URL}/{image_url}"
                
            payload = {
                "id": config.TELEGRAM_CHAT_ID,
                "message": full_msg
            }
            r.rpush("messages_queue", json.dumps(payload, ensure_ascii=False))
        except Exception as e:
            print(f"FAILED TO PUSH CHAT MESSAGE TO REDIS: {e}")
