# -*- coding: utf-8 -*-
import sys
import dateparser
from datetime import datetime
from lib.apicalls import *
from lib.utils import *
from lib.htmlgen import *
from lib.graphsgen import *
from lib.langstrings import *
import warnings
import base64
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

warnings.filterwarnings("ignore", category=UserWarning)

SCOPES = ['https://www.googleapis.com/auth/gmail.send']
# 1. Archivo descargado de Google Cloud
CLIENT_SECRET_FILE = 'lib/credentials.json'
TOKEN_FILE = 'lib/token.json'

msg = getMessages("es")
file_content = ''

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

parser = argparse.ArgumentParser()
parser.add_argument("-x", "--execution", help="Execution Mode", required=False)
parser.add_argument("-t", "--template", help="HTML Template path", required=False)
parser.add_argument("-f", "--facility", help="Facility ID", required=False)
parser.add_argument("-d", "--date", help="Reports date format yyyy-mm", required=False)
parser.add_argument("-c", "--clientname", help="Client Name", required=False)
parser.add_argument("-m", "--clientmail", help="Client Mail", required=False)
parser.add_argument("-r", "--replace", help="Replace old file", required=False)
parser.add_argument("-u", "--force_update", help="Force Report Update (only used on create)", required=False)
parser.add_argument("-w", "--weekly", help="Weekly report", required=False)
args = parser.parse_args()

dirpath = (os.path.dirname(os.path.realpath(__file__)))
os.environ['MPLCONFIGDIR'] = ""+dirpath+"/temp/images/"

def upload_report(pdfFile,data):
  app_id = 1
  api_user = 13510
  api_token = "fc323b1d03569f3be9e598df178017808b8bc9fb"
  month = int(args.date.split("-")[1])
  year = int(args.date.split("-")[0])
  datew = "0"+str(month)+"_"+str(year)
    
  with open(pdfFile, 'rb') as f:

      print(os.path.basename(pdfFile))
      body = {'user':api_user,'app':app_id,'api_token':api_token,'month_year':datew,'facility_id': data}
      files = {'file': (os.path.basename(pdfFile), f, 'application/pdf')}
      apiCall = requests.post('https://api.gc-track.net/fire_monitoring/app/reports/upload_monthly_report.php', files=files, data=body)
      apiCall.encoding = 'utf-8'
      apiResult = json.loads(apiCall.text)

      if apiResult['data'] != "":
          #deleteTempFiles()
          if str(args.execution) == "create":
            print(str(apiResult['data']))
          else:
            print(f"└[El documento se subio correctamente a la nube]")
      else:
        print(f"└[ERROR]")

def createCompleteReport(rDate,rFacility):
    # facilityId = int(args.facility)
    facilityId = int(rFacility)
    facility = getFacilityInfo(facilityId)
    current_date = datetime.today()
    report_date = ''

    if rDate is not None:
        report_date = datetime.strptime(str(rDate),"%Y-%m") 
    else:
        report_date = current_date    

    weekdays = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"]
    months = [
        "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
        "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
    ]

    formatted_date = f"{months[report_date.month-1]}, {report_date.year}"
    param_date = str(report_date.year)+'-'+str(report_date.month-1)
    param_date_api = str(report_date.year)+'-'+str(report_date.month)
    dirname = (months[report_date.month-1]+'_'+str(report_date.year)).upper()
    dirPathm = dirpath+'/temp/reports/monthly/'+dirname


    if args.weekly != 1:
        createReportDir(dirPathm)
    else:
        print("En construccion")

    try:
        convertClientLogo(facility['logo_png_url'])
    except Exception:
        pass

    try:
        if facility['redbox_vendor_logo_png_url']:
            convertCompanyLogo(facility['redbox_vendor_logo_png_url'])
        else:
            convertCompanyLogo(facility['detector_vendor_logo_png_url'])
    except Exception:
        pass


    reportData = getMonthlyReportSingle(facilityId,report_date)['facility_data'][0]
    stateRecords = getStateRecords(facility['redbox_id'],str(param_date_api))

    if args.template is not None:
        file_path = str(args.template)
    else:
        file_path = '/var/www/reporter.gc-track.com/app/res/templates/report_template_monthly.html'    

    with open(file_path, 'r') as file:
        file_content = file.read()

    file_content = file_content.replace("[$facility_name$]",facility['name'])
    file_content = file_content.replace("[$footer_date$]",insertActualDate())
    
    try:
        file_content = file_content.replace("[$facility_address$]",facility['full_address'])
    except TypeError:
        file_content = file_content.replace("[$facility_address$]","")

    try:
        file_content = file_content.replace("[$postal_address$]",facility['postal_address'])
    except TypeError:
        file_content = file_content.replace("[$postal_address$]","")
        
    
    file_content = file_content.replace("[$DATE_HEADER$]",formatted_date)

    try:
        file_content = file_content.replace("[$facility_data$]",getComponentListHtml(facilityId))
    except TypeError:
        file_content = file_content.replace("[$facility_data$]","")

    try:
        file_content = file_content.replace("[$pressure_graph$]",generatePressureGraphHtml(reportData['pressure_component_id'],str(param_date_api)))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")
        
        
        if str(args.execution) != "create":
            print("├── Generando grafica de presion")
        presureGraphExist = 1
    except TypeError:
        file_content = file_content.replace("[$pressure_graph$]","")
        presureGraphExist = 0

    try:
        file_content = file_content.replace("[$jockey_graph$]",generateJockeyGraphHtml(facility['redbox_id'],str(param_date_api)))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")
        
        if str(args.execution) != "create":
            print("├── Generando grafica de jockey")
        jockeyGraphExist = 1
    except TypeError:
        file_content = file_content.replace("[$jockey_graph$]","")
        jockeyGraphExist = 0

    try:
        file_content = file_content.replace("[$alarm_table$]",generateAlarmTableByMonthHtml(facilityId,str(param_date_api)))
        if str(args.execution) != "create":
            print("├── Generando tabla de panel de alarma")
        alarmTableExist = 1
    except TypeError:
        file_content = file_content.replace("[$alarm_table$]","")
        alarmTableExist = 0

    try:
        file_content = file_content.replace("[$alert_table$]",generateAlertHistorybyMonthHtml(stateRecords))
        file_content = file_content.replace("alerts-title-hidden","alerts-title")
        file_content = file_content.replace("alerts-content-hidden","alerts-content")
        

        if str(args.execution) != "create":
            print("├── Generando tabla de alertas en bombas")
        alertTableExist = 1
    except TypeError as error:
        noelements =   f'''
        <table class="activations-table">
            <caption>Alertas generales fuera de mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-start-date">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
            <tr>
               <td colspan="5">No se registraron alertas generales fuera de mantenimiento</td>
            </tr>
            </tbody>
        </table>'''

        file_content = file_content.replace("[$alert_table$]",noelements)
        pumpRunDetailsExist = 0

    try:
        file_content = file_content.replace("[$alert_table_mant$]",generateAlertHistorybyMonthHtmlMant(stateRecords))
        file_content = file_content.replace("alerts-title-hidden","alerts-title")
        file_content = file_content.replace("alerts-content-hidden","alerts-content")
        
        if str(args.execution) != "create":
            print("├── Generando tabla de alertas en bombas en mantenimiento")
        alertTableExist = 1
    except TypeError as error:
        noelements =   f'''
        <table class="activations-table">
            <caption>Alertas generales en mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-start-date">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
            <tr>
               <td colspan="5">No se registraron alertas generales en mantenimiento</td>
            </tr>
            </tbody>
        </table>'''

        file_content = file_content.replace("[$alert_table_mant$]",noelements)
        pumpRunDetailsExist = 0
    
    
    try:
        file_content = file_content.replace("[$pump_count$]",getNewPumpRunCount(stateRecords))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")

        if str(args.execution) != "create":
            print("├── Generando conteos de encendidos en bombas")
        pumpCountExist = 1
    except TypeError as error:
        file_content = file_content.replace("[$pump_count$]","")
        pumpCountExist = 0
     
    try:
        file_content = file_content.replace("[$alarm_count$]",getNewAlertCount(stateRecords))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")

        if str(args.execution) != "create":
            print("├── Generando conteos de alertas en bombas")
        alarmCountExist = 1
    except Exception as error:
        print(error)
        file_content = file_content.replace("[$alarm_count$]","")
        alarmCountExist = 0      
    try:
        file_content = file_content.replace("[$detector_count$]",getDetectorCount(reportData))
        file_content = file_content.replace("alerts-title-hidden","alerts-title")
        file_content = file_content.replace("alerts-content-hidden","alerts-content")
        
        
        if str(args.execution) != "create":
            print("├── Generando conteos en panel de alarmas")
        detectorCountExist = 1
    except TypeError:
        file_content = file_content.replace("[$detector_count$]","")
        detectorCountExist = 0     

    try:
        file_content = file_content.replace("[$pump_run_details$]",generatePumpDetails(stateRecords))
        file_content = file_content.replace("activations-title-hidden","activations-title")
        file_content = file_content.replace("activations-content-hidden","activations-content")

        if str(args.execution) != "create":
            print("├── Generando informacion detallada en bombas")
        pumpRunDetailsExist = 1
    except TypeError as error:
        noelements =   f'''
        <table class="activations-table">
            <caption>Arranques fuera de mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-start-date">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
            <tr>
               <td colspan="5">No se registraron arranques fuera de mantenimiento</td>
            </tr>
            </tbody>
        </table>'''

        file_content = file_content.replace("[$pump_run_details$]",noelements)
        pumpRunDetailsExist = 0
       
    try:
        file_content = file_content.replace("[$pump_run_details_mant$]",generatePumpDetailsMant(stateRecords))
        file_content = file_content.replace("activations-title-hidden","activations-title")
        file_content = file_content.replace("activations-content-hidden","activations-content")

        if str(args.execution) != "create":
            print("├── Generando informacion detallada en bombas en mantenimiento")
        pumpRunDetailsMantExist = 1
    except TypeError as error:
        noelements =   f'''
        <table class="activations-table">
            <caption>Arranques en mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-start-date">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
            <tr>
               <td colspan="5">No se registraron arranques en mantenimiento</td>
            </tr>
            </tbody>
        </table>'''

        file_content = file_content.replace("[$pump_run_details_mant$]",noelements)
        pumpRunDetailsExist = 0    


    with open("./temp/result.html", "w") as f:
        f.write(file_content)

    m = months[(report_date.month)-1][:3]
    pdfname = str(facility["shortname"])+"_"+m+str(report_date.year)[-2:]
    pdfname = pdfname.upper()
    
    generatePDF('result.html','reports/monthly/'+dirname+"/"+pdfname+'.pdf')
    return "/var/www/reporter.gc-track.com/app/temp/reports/monthly/"+dirname+"/"+pdfname+'.pdf'

# def send_new_mail_monthly_old(to,name,month,year,tabledata):
#     fromaddr = "support@gc-track.com"
#     toaddr = to
#     msg = MIMEMultipart()
#     msg['From'] = f"Equipo de Soporte GC-Track <support@gc-track.com>"
#     msg['X-Mailer'] = f"Equipo de Soporte GC-Track"
#     msg['To'] = toaddr
#     msg['Subject'] = "[GC-Track Monitoring System] Reporte mensual de "+month+" 📄"
#     body = ''

#     table_content = ""

#     print(f"┌─[{bcolors.BOLD}"+name+"]")

#     for client_data in tabledata:
#         if client_data['report_url']:
#             print("├── "+client_data['name']+"[🗸]")
            
#             table_content = table_content+'<li>'+client_data['name']+' <a target="_blank" href="'+client_data['report_url']+'"><span style="font-size:small;">[ Descargar ]</span></a></li>'
#         else:
#             print("├── "+client_data['name']+"[𐄂]")
            
#     table= table_content

#     with open(r''+dirpath+'/res/templates/mail_template_monthly.html', 'r') as filea:
#         body = filea.read().replace('%table_content',table).replace('#month#',month).replace('#year#',year)
        
#     context = ssl.create_default_context()
#     msg.attach(MIMEText(body, 'html'))
#     #server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
#     server = smtplib.SMTP('smtp.gmail.com', 587)
#     #server.set_debuglevel(1)
#     server.ehlo()
#     server.starttls()
#     server.ehlo()
#     server.login(fromaddr,'47d*94m",UtFxXs')
#     text = msg.as_string()
#     try:
#       if not len(table_content) == 0:
#           mail_send =  server.sendmail(fromaddr, toaddr, text)
#       else:
#           raise ValueError("No hay reportes con url, por eso no se envio correo")    
#     except smtplib.SMTPRecipientsRefused:
#         print("recipient address must contain a domain")
    
#     server.quit()
#     server.close()

def get_gmail_service():
    creds = None
    
    # 1. Leer el token guardado si ya existe
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    
    # 2. Si no hay token o expiró, solicitar autorización
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
            
            # Usar puerto fijo 8080 en lugar de aleatorio
            creds = flow.run_local_server(
                host='localhost',
                port=8080,
                open_browser=False
            )
            
        # 3. Guardar el nuevo token generado
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())

    return build('gmail', 'v1', credentials=creds)

def send_new_mail_monthly(to, name, month, year, tabledata):
    fromaddr = "support@gc-track.com"
    toaddr = to

    # 1. Construir la estructura del correo MIME
    msg = MIMEMultipart()
    msg['From'] = f"Equipo de Soporte GC-Track <{fromaddr}>"
    msg['X-Mailer'] = "Equipo de Soporte GC-Track"
    msg['To'] = toaddr
    msg['Subject'] = f"[GC-Track Monitoring System] Reporte mensual de {month} 📄"

    table_content = ""
    print(f"┌─[{name}]")

    for client_data in tabledata:
        if client_data.get('report_url'):
            print("├── " + client_data['name'] + "[🗸]")
            table_content = table_content+'<li><a target="_blank" href="'+client_data['report_url']+'">'+client_data['name']+'</a></li>'
        else:
            print("├── " + client_data['name'] + "[𐄂]")

    # 2. Leer y reemplazar variables en el template HTML
    with open(os.path.join(dirpath, 'res/templates/mail_template_monthly.html'), 'r') as filea:
        body = filea.read().replace('%table_content', table_content).replace('#month#', month).replace('#year#', year)

    msg.attach(MIMEText(body, 'html'))

    # 3. Validar si hay contenido antes de enviar
    if not table_content:
        raise ValueError("No hay reportes con url, por eso no se envio correo")

    # 4. Enviar mediante la API de Gmail (OAuth2)
    try:
        service = get_gmail_service()
        
        # Formatear el mensaje MIME a Base64 URL-Safe exigido por Gmail API
        raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode('utf-8')
        send_message = {'raw': raw_message}

        sent = service.users().messages().send(userId="me", body=send_message).execute()
        print(f"Correo enviado exitosamente. ID del mensaje: {sent['id']}")

    except Exception as error:
        print(f"Error al enviar el correo mediante OAuth2: {error}")

def send_new_mail_weekly(to, name, month,tabledata):
    fromaddr = "support@gc-track.com"
    toaddr = to
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "[GC-Track Monitoring System] Reporte mensual de "+month+" 📄"
    body = ''
    
    
    table_content = ""
    for client_data in tabledata:
        if client_data['url']:
            print("├── "+client_data['facility']+"[🗸]")
            client_data['url']
            table_content = table_content+'<li><a target="_blank" style="color: #fff;" href="'+client_data['url']+'">'+client_data['facility']+'</a></li>'
        else:
            print("├── "+client_data['facility']+"[𐄂]")
            
    table= table_content
    
    with open(r''+dirpath+'/res/templates/mail_template.html', 'r') as filea:
        body = filea.read().replace('%table_content',table)
        
    context = ssl.create_default_context()
    msg.attach(MIMEText(body, 'html'))
    #server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
    server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
    server.login(fromaddr, "gldqkbvgpysupvso")
    text = msg.as_string()
    try:
      if not len(table_content) == 0:
          mail_send =  server.sendmail(fromaddr, toaddr, text)
      else:
          raise ValueError("No hay reportes con url, por eso no se envio correo")    
    except smtplib.SMTPRecipientsRefused:
        print("recipient address must contain a domain")
    server.quit()
    server.close()

if str(args.execution) == "report":
    os.system('clear')
    print("╔════════════════════════════════════════╗")
    print("║      GENERANDO REPORTES MENSUALES      ║")
    print("╚════════════════════════════════════════╝")
    print("")
    month_adjust = 1
    today_a_month_ago = date.today() - relativedelta(months=1)
    v = requests.post('https://api.gc-track.net/fire_monitoring/app/list_prod_facilities.php')
    v.encoding = 'utf-8'
    prodfac = json.loads(v.text)
    prod = prodfac["facilities"]
    
    for p in prod:
            print(f"┌─[{bcolors.BOLD}Compilando "+p["name"]+f" ID: {bcolors.WARNING}"+str(p["id"])+f"{bcolors.ENDC}]")
            upload_report(createCompleteReport(args.date,p["id"]),p["id"])
            print(" ")
            time.sleep(2)

if str(args.execution) == "single":
    os.system('clear')
    print("╔════════════════════════════════════════╗")
    print("║      GENERANDO REPORTE SENCILLO        ║")
    print("╚════════════════════════════════════════╝")
    print("")
    upload_report(createCompleteReport(args.date,args.facility),args.facility)

if str(args.execution) == "create":
    report_date = datetime.strptime(str(args.date),"%Y-%m") 
    date_p = str(report_date.month)+"_"+str(report_date.year)

    #aqui forzara a crear y subir un reporte nuevo
    
    if str(args.force_update) == "1":
        upload_report(createCompleteReport(args.date,args.facility),args.facility)
    else:
        #esta parte buscara su existe un reporte, si existe, regresara tu url
        if find_report(args.facility,date_p)['records'] != '':
            print(find_report(args.facility,date_p)['records'])
        else:
            #En caso de no existir, se creara un reporte nuevo y regresara la url una vez creado
            upload_report(createCompleteReport(args.date,args.facility),args.facility)      

if str(args.execution) == "revision":
    os.system('clear')
    print("╔════════════════════════════════════════════════════╗")
    print("║      GENERANDO DE REVISION REPORTES MENSUALES      ║")
    print("╚════════════════════════════════════════════════════╝")
    print("")
    month_adjust = 1
    today_a_month_ago = date.today() - relativedelta(months=1)
    v = requests.post('https://api.gc-track.net/fire_monitoring/app/list_rev_facilities.php')
    v.encoding = 'utf-8'
    prodfac = json.loads(v.text)
    prod = prodfac["facilities"]
    for p in prod:
            print(f"┌─[{bcolors.BOLD}Compilando "+p["name"]+f" ID: {bcolors.WARNING}"+str(p["id"])+f"{bcolors.ENDC}]")
            upload_report(createCompleteReport(args.date,p["id"]),p["id"])
            time.sleep(5)

if str(args.execution) == "revisionless":
    os.system('clear')
    month_adjust = 1
    today_a_month_ago = date.today() - relativedelta(months=1)
    v = requests.post('https://api.gc-track.net/fire_monitoring/app/list_rev_facilities.php')
    v.encoding = 'utf-8'
    prodfac = json.loads(v.text)
    prod = prodfac["facilities"]
    for p in prod:
            upload_report(createCompleteReport(args.date,p["id"]),p["id"])
            time.sleep(5)

if str(args.execution) == "mail":
    os.system('clear')
    print("╔════════════════════════════════════════╗")
    print("║            ENVIO DE CORREOS            ║")
    print("╚════════════════════════════════════════╝")
    print("")
    mail_clients = []
    app_id = 1
    api_user = 13510
    api_token = "fc323b1d03569f3be9e598df178017808b8bc9fb"
    
    today_a_month_ago = date.today() - relativedelta(months=1)
    if args.date:
        year_str, month_str = args.date.split("-")
        datew = f"{month_str.zfill(2)}_{year_str}"
    else:
        datew = str(today_a_month_ago.month)+"_"+str(today_a_month_ago.year)    
    
    body = {'user':api_user,'app':app_id,'api_token':api_token,'month_year':datew}
    r = requests.post('https://reporter.gc-track.com/api/app/reports/get_usersFacilities_monthly_reporter.php', body)
    r.encoding = 'utf-8'
    response = json.loads(r.text)
    data = response["data"]

    for user in data:
        try:
            user_facilities = user.get('facilities', [])

            #send_new_mail_monthly(user["email"],user['name'],months[int(args.date.split("-")[1])],year_str,user_facilities)
            send_new_mail_monthly("erick.rodriguez@uabc.edu.mx",user['name'],months[int(args.date.split("-")[1])],year_str,user_facilities)
            #send_new_mail_monthly("arnulfo.desantiago@gc-track.com",user['name'],months[int(args.date.split("-")[1])],year_str,user_facilities)
            #send_new_mail_monthly("erick.rodriguez@uabc.edu.mx",user['name'],months[int(args.date.split("-")[1])],year_str,user_facilities)
            send_new_mail_monthly("jorge.parra@gc-track.com",user['name'],months[int(args.date.split("-")[1])],year_str,user_facilities)
            print(f"└[ {bcolors.BOLD}{bcolors.OKGREEN}Correo enviado {bcolors.ENDC}]")
            print(" ")
            time.sleep(10)
        
        except Exception as e:
            print(f"└[{bcolors.BOLD}{bcolors.FAIL}Falló, razon: "+str(e)+f"{bcolors.ENDC}]")
            print(" ")
            continue
        
        
