import json
import os
from datetime import datetime
from .legal import LegalCheck
from .geography import ZoneDetector

class ContactScorer:
    def __init__(self):
        base_path = os.path.dirname(__file__)
        self.rules_path = os.path.join(base_path, 'rules.json')
        
        with open(self.rules_path, 'r') as f:
            self.rules_config = json.load(f)
            
        self.legal_checker = LegalCheck(self.rules_path)
        self.zone_detector = ZoneDetector()

    def get_contact_score(self, phone: str, region_hint=None, timestamp: datetime = None):
        """
        Evalúa si es un buen momento para contactar.
        Retorna dict con score, status, y reason.
        """
        if timestamp is None:
            timestamp = datetime.now()

        # 1. Validación Legal (CRÍTICO)
        is_legal, legal_reason = self.legal_checker.is_legal(timestamp)
        if not is_legal:
            return {
                "score": 0,
                "status": "PROHIBITED",
                "reason": legal_reason,
                "region": "Unknown"
            }

        # 2. Detección de Región
        # Si el usuario da un hint (ej: base de datos), lo usamos. Si no, detectamos.
        if region_hint:
            region = region_hint
        else:
            region = self.zone_detector.detect_region(phone)
            
        # Normalizar nombre de region para buscar en reglas
        region_key = region.lower()
        if region_key not in self.rules_config["regions"]:
            region_key = "general" # Fallback

        region_rules = self.rules_config["regions"][region_key]
        current_time_str = timestamp.strftime("%H:%M")

        # 3. Evaluar Zonas Muertas (Almuerzo / Cultural)
        for start, end in region_rules["dead_zones"]:
            if start <= current_time_str < end:
                 return {
                    "score": 20,
                    "status": "POOR",
                    "reason": f"Zona Muerta Cultural ({region})",
                    "region": region
                }

        # 4. Evaluar Zonas Prioritarias (Ventanas de oportunidad)
        for start, end in region_rules["priority_slots"]:
             if start <= current_time_str < end:
                 return {
                    "score": 95,
                    "status": "EXCELLENT",
                    "reason": f"Franja Alta Efectividad ({region})",
                    "region": region
                }

        # 5. Resto del horario
        return {
            "score": 60,
            "status": "NORMAL",
            "reason": "Horario Hábil Estándar",
            "region": region
        }
