"""
AidePlus Blueprint - Handles AidePlus device API endpoints
"""

import logging
from flask import Blueprint, request, jsonify
import paho.mqtt.publish as mqtt_publish
from flask_jwt_extended import jwt_required
from flask import current_app
from common.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR

logger = logging.getLogger("median.aideplus")

# MQTT Topics
SERVER_EVENTS_TOPIC = "server/events/#"
DEVICE_WILDCARD_TOPIC = "devices/#"


def get_mqtt_settings():
    """Get MQTT broker settings from app configuration"""
    if current_app:
        return (current_app.config.get("MQTT_BROKER_URL"), current_app.config.get("MQTT_BROKER_PORT"))
    # Default values from .env if app context not available
    return "172.24.2.78", 1883


MQTT_BROKER, MQTT_PORT = get_mqtt_settings()
MQTT_KEEPALIVE = 60
MQTT_CLIENT_ID = "median_web_server"

# Use the mqtt_handler for publishing messages

# Initialize blueprint
aideplus_blueprint = Blueprint("aideplus", __name__, url_prefix="/api/aideplus")


# MQTT publish endpoint
@aideplus_blueprint.route("mqtt/publish", methods=["POST"])
@jwt_required()
def publish_mqtt():
    """
    Publish a message to the MQTT broker

    Request JSON:
    {
        "topic": "topic/path",
        "message": "message content or JSON string",
        "retain": false,
        "qos": 1
    }
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({"success": False, "error": "No request data provided"}), 400

        # Extract required fields
        topic = data.get("topic")
        message = data.get("message")
        retain = data.get("retain", False)
        qos = data.get("qos", 1)

        if not topic or not message:
            return jsonify({"success": False, "error": "Missing required fields (topic, message)"}), 400

        # Log the MQTT publish request
        logger.info(f"Publishing to MQTT - Topic: {topic}, Message: {message[:100]}...")

        # Publish the message to MQTT broker
        mqtt_publish.single(
            topic=topic,
            payload=message,
            qos=qos,
            retain=retain,
            hostname=MQTT_BROKER,
            port=MQTT_PORT,
            client_id=MQTT_CLIENT_ID,
        )

        logger.info(f"Successfully published MQTT message to {topic}")
        return {"success": True, "message": "Message published successfully"}, HTTP_200_OK

    except Exception as e:
        logger.error(f"Error publishing MQTT message: {str(e)}", exc_info=True)
        return {"success": False, "error": str(e)}, HTTP_500_INTERNAL_SERVER_ERROR
