
from argparse import ArgumentParser
import signal
import os
import logging


from Controller import Controller
from MQTTClient import MQTTClient

logging.basicConfig(level=logging.INFO)

signal.signal(signal.SIGINT, signal.SIG_DFL) # Allow Ctrl+C to terminate the script
notifiers = [] # List to hold the notifiers


def validate_arguments(parser: ArgumentParser, ip: str, port: int, token: str, username: str, password: str, crt: str):
    """
    Validate the command line arguments.
    """
    if port < 0 or port > 65535:
        parser.error("Port number must be between 0 and 65535.")
    
    if not username and password or username and not password: # If one is provided, the other must be provided as well
        parser.error("Username and password are required if one is provided.")

    if crt:
        if not os.path.isfile(crt) or not os.access(crt, os.R_OK): # Check if the certificate file exists and is readable
            parser.error(f"Certificate file {crt} does not exist or is not readable.")
        if not crt.endswith(".crt"): # Check if the certificate file has the correct extension
            parser.error(f"Certificate file {crt} must be a .crt file.")


def get_arguments():
    """
    Parse command line arguments.
    """
    parser = ArgumentParser(description="Telegram Notifier Service")
    parser.add_argument("-i", "--ip", type=str, required=True, help="MQTT broker ip address (Required)")
    parser.add_argument("-p", "--port", type=int, required=True, help="MQTT broker port (Required)")
    parser.add_argument("-t", "--token", type=str, required=True, help="Telegram bot token (Required)")
    parser.add_argument("-U", "--username", type=str, required=False, help="Username for the MQTT broker (Optional)")
    parser.add_argument("-P", "--password", type=str, required=False, help="Password for the MQTT broker (Optional)")
    parser.add_argument("-c", "--crt", type=str, required=False, help="Path to the TLS certificate file (Optional)")
    arguments = parser.parse_args()

    ip, port = arguments.ip, arguments.port
    token = arguments.token
    username, password = arguments.username, arguments.password
    crt = arguments.crt
    validate_arguments(parser, ip, port, token, username, password, crt)
    return ip, port, token, username, password, crt

def main():
    """
    Main function to run the Telegram notifier service.
    """
    ip, port, token, username, password, crt = get_arguments()
    client = MQTTClient(ip, port, username, password, crt)
    controller = Controller(client, token)
    controller.run()
    


if __name__ == "__main__":
    main()
    

