"""
Calendar file generator for AquaCrop (.CAL files)
"""

import os
from aquacrop.constants import Constants

def generate_calendar_file(
    file_path: str,
    description: str,
    onset_mode: int = 0,  # 0=fixed date, 1=generated by criteria
    
    # Fixed date parameters (for mode 0)
    day_number: int = 1,
    
    # Criteria parameters (for mode 1)
    window_start_day: int = 1,
    window_length: int = 90,
    criterion_number: int = 1,
    criterion_value: float = 20.0,
    successive_days: int = 1,
    occurrences: int = 1
) -> str:
    """
    Generate an AquaCrop calendar file (.CAL)
    
    Args:
        file_path: Path to write the file
        description: Calendar description
        onset_mode: Calendar mode (0=fixed date, 1=generated by criteria)
        
        # Fixed date parameters (for mode 0)
        day_number: Day number (1-366) for onset of growing period
        
        # Criteria parameters (for mode 1)
        window_start_day: Day-number (1-365) of start of time window
        window_length: Length (days) of the time window
        criterion_number: Criterion number for generation of onset:
            - 1: Cumulative rainfall since start of time period
            - 2: Observed rainfall during successive days
            - 3: 10-day rainfall threshold
            - 4: 10-day rainfall exceeds percentage of 10-day ETo
            - 11: Minimum air temperature threshold
            - 12: Average air temperature threshold
            - 13: Sum of growing degree days for successive days
            - 14: Cumulative growing degree days since time period start
        criterion_value: Value for the specified criterion (mm, °C, degree-days, or %)
        successive_days: Number of successive days for criterion
        occurrences: Number of occurrences before criterion applies (max = 3)
    
    Returns:
        The path to the generated file
    """
    # Validation
    if day_number < 1 or day_number > 366:
        raise ValueError("day_number must be between 1 and 366")
    
    if window_start_day < 1 or window_start_day > 365:
        raise ValueError("window_start_day must be between 1 and 365")
    
    if criterion_number not in [1, 2, 3, 4, 11, 12, 13, 14]:
        raise ValueError("criterion_number must be one of: 1, 2, 3, 4, 11, 12, 13, 14")
    
    if occurrences < 1 or occurrences > 3:
        raise ValueError("occurrences must be between 1 and 3")
    
    # Generate file content based on mode
    lines = [
        f"{description}",
        f"{Constants.AQUACROP_VERSION_NUMBER} : AquaCrop Version ({Constants.AQUACROP_VERSION_DATE})",
        f"{onset_mode} : The onset of the growing period is {'generated by a rainfall or air temperature criterion' if onset_mode == 1 else 'fixed on a specific date'}"
    ]
    
    if onset_mode == 0:
        # Fixed date mode
        lines.extend([
            f"-9 : Day-number (1 ... 366) of the Start of the time window for the onset criterion: Not applicable",
            f"-9 : Length (days) of the time window for the onset criterion: Not applicable",
            f"{day_number} : Day-number (1 ... 366) for the onset of the growing period",
            f"-9 : Preset value for generation of the onset: Not applicable",
            f"-9 : Number of successive days: Not applicable",
            f"-9 : Number of occurrences: Not applicable"
        ])
    else:
        # Criteria-based mode
        criterion_type = "Observed rainfall" if criterion_number == 2 else \
                         "Cumulative rainfall" if criterion_number == 1 else \
                         "10-day rainfall" if criterion_number == 3 else \
                         "10-day rainfall/ETo ratio" if criterion_number == 4 else \
                         "Minimum air temperature" if criterion_number == 11 else \
                         "Average air temperature" if criterion_number == 12 else \
                         "Sum of Growing-degree days" if criterion_number == 13 else \
                         "Cumulative Growing-degree days"
        
        lines.extend([
            f"{window_start_day} : Day-number (1 ... 366) of the Start of the time window for the onset criterion",
            f"{window_length} : Length (days) of the time window for the onset criterion",
            f"{criterion_number} : Criterion Nr ({criterion_type})",
            f"{criterion_value} : Preset value of {criterion_type} ({_get_criterion_unit(criterion_number)})",
            f"{successive_days} : Number of successive days for the onset criterion",
            f"{occurrences} : Number of occurrences before the onset criterion applies (max = 3)"
        ])
    
    content = "\n".join(lines)
    
    if file_path:
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, 'w') as f:
            f.write(content)
    
    return file_path

def _get_criterion_unit(criterion_number: int) -> str:
    """Get the appropriate unit for the criterion"""
    if criterion_number in [1, 2, 3]:  # Rainfall criteria
        return "mm"
    elif criterion_number == 4:  # Rainfall/ETo ratio
        return "%"
    elif criterion_number in [11, 12]:  # Temperature criteria
        return "°C" 
    else:  # Growing degree days criteria
        return "degree-days"