import boto3
import json
import os
from dotenv import load_dotenv
from typing import List, Dict, Any

# Cargar variables de entorno
load_dotenv()

class BedrockService:
    def __init__(self):
        # Obtener credenciales del entorno
        aws_access_key = os.getenv("AWS_ACCESS_KEY_ID")
        aws_secret_key = os.getenv("AWS_SECRET_ACCESS_KEY")
        
        # Imprimir para debug (¡quitar en producción!)
        print(f"Using AWS region: {"eu-central-1"}")
        print(f"Access key exists: {aws_access_key is not None}")
        
        # Inicializar cliente
        if aws_access_key and aws_secret_key:
            self.client = boto3.client(
                'bedrock-runtime',
                region_name="eu-central-1",
                aws_access_key_id=aws_access_key,
                aws_secret_access_key=aws_secret_key
            )
        else:
            # Intentar usar credenciales del sistema
            self.client = boto3.client(
                'bedrock-runtime',
                region_name="eu-central-1"
            )
            
        self.model_id = "anthropic.claude-v2:1"

    def generate_response(self, message: str, services: List[Dict[str, Any]]) -> str:
        # Convertir la lista de diccionarios a un formato legible
        context_lines = []
        for service in services:
            category = service.get('category', '')
            name = service.get('name', '')
            details = service.get('details', {})
            description = details.get('description', '')
            
            # Añadir información básica
            service_info = f"- {category} | {name}: {description}"
            
            # Añadir detalles específicos según la categoría
            if category == "Espai":
                espai_type = details.get('espai_type', '')
                capacity = f"{details.get('capacitat_min', 0)}-{details.get('capacitat_max', 0)}"
                price = details.get('price', 0)
                characteristics = ", ".join(details.get('caracteristicas', []))
                service_info += f" | Tipo: {espai_type} | Capacidad: {capacity} | Precio: {price}€ | Características: {characteristics}"
            
            elif category == "Catering":
                catering_type = details.get('catering_type', '')
                price_per_person = details.get('price_per_person', 0)
                guests = f"{details.get('min_guests', 0)}-{details.get('max_guests', 0)}"
                menu = ", ".join(details.get('menu_options', []))
                service_info += f" | Tipo: {catering_type} | Precio por persona: {price_per_person}€ | Invitados: {guests} | Menú: {menu}"
            
            elif category == "Musica":
                musica_type = details.get('musica_type', '')
                price = details.get('price', 0)
                genres = ", ".join(details.get('genres', []))
                service_info += f" | Tipo: {musica_type} | Precio: {price}€ | Géneros: {genres}"
            
            elif category == "Decoració":
                decoracio_type = details.get('decoracio_type', '')
                price = details.get('price', 0)
                themes = ", ".join(details.get('themes', []))
                service_info += f" | Tipo: {decoracio_type} | Precio: {price}€ | Temas: {themes}"
            
            elif category == "Mobiliari":
                mobiliari_type = details.get('mobiliari_type', '')
                price = details.get('price', 0)
                materials = ", ".join(details.get('materials', []))
                colors = ", ".join(details.get('colors', []))
                service_info += f" | Tipo: {mobiliari_type} | Precio: {price}€ | Materiales: {materials} | Colores: {colors}"
            
            elif category == "Fotografia":
                fotografia_type = details.get('fotografia_type', '')
                price = details.get('price', 0)
                specialties = ", ".join(details.get('specialties', []))
                service_info += f" | Tipo: {fotografia_type} | Precio: {price}€ | Especialidades: {specialties}"
            
            context_lines.append(service_info)
        
        context = "\n".join(context_lines)
        
        prompt = f"\n\nHuman: {message}\n\nContexto de servicios disponibles:\n{context}\n\nImportante: Revisa TODOS los servicios disponibles y mencionados arriba antes de responder. Asegúrate que tu respuesta sea coherente con los servicios listados y no contradigas la información proporcionada.\n\nAssistant:"
        
        request_body = {
            "prompt": prompt,
            "max_tokens_to_sample": 400,
            "temperature": 0.5,
            "top_k": 250,
            "top_p": 1,
            "stop_sequences": ["\n\nHuman:"],
            "anthropic_version": "bedrock-2023-05-31"
        }

        try:
            # Convertir a string JSON
            json_body = json.dumps(request_body)
            
            # Llamar a Bedrock con el formato exacto que especifica AWS
            response = self.client.invoke_model(
                modelId=self.model_id,
                contentType="application/json",
                accept="*/*",
                body=json_body
            )
            
            # Procesar la respuesta
            response_body = json.loads(response['body'].read())
            return response_body.get('completion', 'No se pudo generar una respuesta')
            
        except Exception as e:
            print(f"Error detallado en Bedrock: {str(e)}")
            return f"Error al procesar la solicitud: {str(e)}" 