import datetime
from datetime import date
import holidays

# Configuration
YEARS_TO_GENERATE = [2025, 2026]
COUNTRY_CODE = "DE"
SUB_REGION = "BY" # Bayern (Wackler HQ)

def generate_crm_script():
    print(f"Generating CRMScript for Holidays ({COUNTRY_CODE}-{SUB_REGION})...")
    
    # 1. Calculate Holidays
    holidays_list = []
    de_holidays = holidays.Country(COUNTRY_CODE, subdiv=SUB_REGION)
    
    for year in YEARS_TO_GENERATE:
        for date_obj, name in de_holidays.items():
            if date_obj.year == year:
                holidays_list.append((date_obj, name))
    
    # Sort by date
    holidays_list.sort(key=lambda x: x[0])
    
    # 2. Generate CRMScript Code
    script = f"// --- AUTO-GENERATED HOLIDAY IMPORT SCRIPT ---
"
    script += f"// Generated for: {COUNTRY_CODE}-{SUB_REGION} (Years: {YEARS_TO_GENERATE})\n"
    script += f"// Target Table: y_holidays (Must exist! Columns: x_date, x_name)\n\n"
    
    script += "Integer count = 0;
"
    script += "DateTime date;
"
    script += "String name;
\n"
    
    for d, name in holidays_list:
        # Format date for CRMScript (usually specific format required, depends on locale but DateTime can parse ISO often)
        # Better: use explicit construction or string
        date_str = d.strftime("%Y-%m-%d")
        
        script += f"date = String(\"{date_str}\").toDateTime();\n"
        script += f"name = \"{name}\";\n"
        
        # Check if exists to avoid dupes (pseudo-code, adapting to likely CRMScript API)
        # Usually we use specific SearchEngine or similar.
        # Simple version: Just insert. Admin should clear table before run if needed.
        
        script += f"// Inserting {date_str} - {name}\n"
        script += "GenericEntity holiday = getDatabaseConnection().createGenericEntity(\"y_holidays\");\n"
        script += "holiday.setValue(\"x_date\", date);
"
        script += "holiday.setValue(\"x_name\", name);
"
        script += "holiday.save();\n"
        script += "count++;\n\n"

    script += "print(\"Imported \" + count.toString() + \" holidays.\");\n"
    
    # 3. Output
    output_filename = "import_holidays_CRMSCRIPT.txt"
    with open(output_filename, "w", encoding="utf-8") as f:
        f.write(script)
        
    print(f"✅ CRMScript generated: {output_filename}")
    print("👉 Copy the content of this file and run it in SuperOffice (Settings -> CRMScript -> Execute).")

if __name__ == "__main__":
    generate_crm_script()
