import os
from datetime import datetime, timedelta
from copernicusmarine import subset
import subprocess

class CopernicusDownloader:
    def __init__(self, username="", password=""):
        self.dataset_id = "cmems_mod_ibi_phy_anfc_0.027deg-2D_PT1H-m"
        self.username = username
        self.password = password
        self.output_file = os.path.join(os.getcwd(), "downloads", "download.nc")
 
    def download(self, lat_min, lat_max, lon_min, lon_max, days):
        today = datetime.utcnow()
        start_date = today.strftime("%Y-%m-%dT00:00:00")
        end_date = (today + timedelta(days=days)).strftime("%Y-%m-%dT23:00:00")

        save_dir = os.path.join(os.getcwd(), "downloads")
        os.makedirs(save_dir, exist_ok=True)

        subset(
            dataset_id=self.dataset_id,
            output_filename=self.output_file,
            variables=["zos", "uo", "vo", "thetao"],
            minimum_longitude=lon_min,
            maximum_longitude=lon_max,
            minimum_latitude=lat_min,
            maximum_latitude=lat_max,
            start_datetime=start_date,
            end_datetime=end_date,
            username=self.username,
            password=self.password
        )

    def convert_to_grib2(self, input_path=None, output_path=None):
        input_path = input_path or self.output_file
        output_path = output_path or input_path.replace(".nc", ".grib2")

        if not os.path.exists(input_path):
            raise FileNotFoundError(f"Fichier introuvable : {input_path}")

        try:
            subprocess.run(["cdo", "-f", "grb2", "copy", input_path, output_path], check=True)
            return output_path
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"Erreur lors de la conversion avec CDO : {e}")
