#!/usr/bin/env
'''
Creation date: 2020-02-05
Creator : sebastien durocher 
Python version : 3.7
Modifier par Assad Najem le 26/01/2026

********
Si jamais il faut changer le scripte de place, il faut modifier la tÃ¢che dans le planificateur. La tÃ¢che s'appelle "chercher prÃ©visions" et il faut que l'argument soit au chemin du scripte

Updates:
- 20/10/2020 : Now automatically determines the path of the script
- 7/2/2024 : XmlToMeteo.exe no longer running from M:, but rather from C:\scripts\XmlToMeteo

Purpose:
- This will update four files (TroisJours71, TroisJours73, ApresTroisJoursB55, ApresTroisJoursUL55)
- It will go read the xml meteocode from env can and copy paste the content within their respective files
- The exe XmlToMeteo.exe can then be used to read the four xml files to produce fancy pretty weather bulletins
- Currently the four xml files are downloaded where this python script is located. If we want to change this, then we need to manually change the path variable at line 39

Notes:
- Four different meteocode numbers:
    - FPCN71, FPCN73, FPUL55, FPQB55 (these represents specific areas in quebec)
    - FPCN71 (day 1 and 2) + FPUL55 (day 3 to 5) = west of QC;
    - FPCN73 + FPQB55 : center and north of QC.
	
	

'''
from bs4 import BeautifulSoup
import requests
import re
import os

####################


#Get latest meteocode data for each number
print('Fetching xml for meteocode')

#path = "M:\\Previsions\\" # Modify/uncomment this in case you want the four xml files to be downloaded elsewhere. Must also put in comment the subsequent paragraph. 
#
# Automatically determine the path of the script and thus the path where the four xml files will be downloaded
#abspath = os.path.abspath(__file__)
#dname = os.path.dirname(abspath)
#os.chdir(dname)
#path = os.getcwd() + "\\"
path = "\\\\IRDAAMETEO01.irda.irda.qc.ca\\meteo\\Previsions\\"
#path = "M:\\Previsions\\"
print(f"Loading to {path}")

base_url = "https://dd.weather.gc.ca/today/meteocode/que/cmml/"
Pre3_West_QC = 'FPCN71'
Post3_West_QC = 'FPUL55'
Pre3_Center_QC = "FPCN73"
Post3_Center_QC = "FPQB55"
All_codes = [Pre3_West_QC,Post3_West_QC,Pre3_Center_QC,Post3_Center_QC]
All_Out_filenames = ['TroisJours71.xml','ApresTroisJoursUL55.xml','TroisJours73.xml','ApresTroisJoursB55.xml']
r = requests.get(base_url, timeout=30)
r.raise_for_status()
page = r.text
# print(page)
soup = BeautifulSoup(page, 'html.parser')
#Loop through all urls of the website

for i in range(0,4):
    xml_url = [node.get('href') for node in soup.find_all('a', string=re.compile(All_codes[i]))]
    # remove empty hrefs
    xml_url = [u for u in xml_url if u]
    # remove those containing 'AMD'
    xml_url = [u for u in xml_url if 'AMD' not in u]
    if not xml_url:
        raise RuntimeError(f"Aucun fichier trouvé pour {All_codes[i]} à {base_url}")
    # choisir le plus récent basé sur le nom TRANSMIT.CODE.MM.DD.HHMMZ.xml
    def _key(u):
        m = re.search(r"\.(\d{2})\.(\d{2})\.(\d{4})Z\.xml$", u)
        return (m.group(1)+m.group(2)+m.group(3)) if m else ''
    latest_href = max(xml_url, key=_key)
    latest_xml_url = base_url + latest_href
    #remove those containing 'AMD' and get the last one (most recent)
    #Read the content of the xml
    resp = requests.get(latest_xml_url, timeout=60)
    resp.raise_for_status()
    #Save the content to a specific filename
    with open(path+All_Out_filenames[i],'wb') as f:
        f.write(resp.content)

print('Done')
