import json
import os
from datetime import datetime, time
import holidays

class LegalCheck:
    def __init__(self, rules_path=None):
        if rules_path is None:
             base_path = os.path.dirname(__file__)
             rules_path = os.path.join(base_path, 'rules.json')
        
        with open(rules_path, 'r') as f:
            self.rules = json.load(f)["legal"]
            
        self.co_holidays = holidays.Colombia()

    def is_legal(self, timestamp: datetime):
        """
        Valida si es legal contactar en la fecha y hora dada.
        Retorna (bool, razon)
        """
        # 1. Festivos y Domingos
        if timestamp.date() in self.co_holidays:
            return False, "Es Festivo en Colombia"
        
        if timestamp.weekday() == 6: # Domingo
            if not self.rules["sunday_holiday"]["allowed"]:
                return False, "Domingo (Prohibido)"

        # 2. Horarios Sábados
        current_time_str = timestamp.strftime("%H:%M")
        if timestamp.weekday() == 5: # Sábado
            start = self.rules["saturday"]["start"]
            end = self.rules["saturday"]["end"]
            if not (start <= current_time_str <= end):
                return False, f"Fuera de horario Sábado ({start}-{end})"
            
        # 3. Horarios Lunes a Viernes
        else:
            start = self.rules["weekdays"]["start"]
            end = self.rules["weekdays"]["end"]
            if not (start <= current_time_str <= end):
                return False, f"Fuera de horario habil ({start}-{end})"

        return True, "Legal"
