"""
This module contains the function to configure the ESP32-CAM with the Wi-Fi and MQTT credentials.
"""

import requests
import logging

ESP32_IP = "192.168.4.1"
API_URL = f"http://{ESP32_IP}/configure" 


def configure_esp32(wifi_ssid: str, wifi_password: str, broker_ip: str, broker_port: int, broker_username: str, broker_password: str, tls_cert: str) -> bool:
    """
    This function sends a POST request to the ESP32-CAM to configure the Wi-Fi and MQTT credentials.

    Parameters:
    - wifi_ssid: The Wi-Fi SSID
    - wifi_password: The Wi-Fi password
    - broker_ip: The MQTT broker IP address
    - broker_port: The MQTT broker port
    - broker_username: The MQTT broker username
    - broker_password: The MQTT broker password
    - tls_cert: The TLS certificate

    Returns:
    - True if the credentials were configured successfully
    - False if there was an error configuring the credentials

    Raises:
    - Exception if there was an error connecting to the ESP32-CAM
    """
    data = {
            "wifi_ssid": wifi_ssid,
            "wifi_password": wifi_password,
            "mqtt_broker_address": broker_ip,
            "mqtt_port": broker_port,
            "mqtt_user": broker_username,
            "mqtt_pass": broker_password,
            "tls_certificate": tls_cert
    } 
    try:
        res = requests.post(url=API_URL, json=data, timeout=5)
    except Exception as e:
        logging.error(f"Error configuring credentials: {e}")
        raise Exception("Cannot connect to ESP32. Please ensure that you are connected to ESP32-CAM's Wi-Fi network")

    if res.status_code == 200:
        logging.info("Credentials configured successfully")
        return True
    else:
        logging.error("Error configuring credentials")
        return False
    