from langchain_openai import ChatOpenAI
from langchain_core.prompts.chat import PromptTemplate
from langchain_community.vectorstores import Milvus
from langchain_openai import OpenAIEmbeddings

from dotenv import load_dotenv
import os
load_dotenv()
API_KEY_OPENAI=os.getenv("API_KEY_OPENAI")
HOST_MILVUS=os.getenv("HOST_MILVUS")
DB_NAME_MILVUS=os.getenv("DB_NAME_MILVUS")

def milvus(collection_name: str):
    embeddings = OpenAIEmbeddings(
        model="text-embedding-3-large",
        openai_api_key=API_KEY_OPENAI,
    )
    return Milvus(
        embeddings,
        collection_name=collection_name,
        connection_args={
            "db_name": DB_NAME_MILVUS,
            "host": HOST_MILVUS,
            "port": "19530",
        },
    )


def clasificacion(
    pregunta: str,
    contexto: str,
):
    llm = ChatOpenAI(
        temperature=0.2,
        model="gpt-3.5-turbo-0125",
        openai_api_key=API_KEY_OPENAI,
    )
    template = (
        """si la siguiente pregunta: {question}, trata sobre """
        + contexto
        + """ si es asi devuelve la palabra 'SI' caso contrario la palabra 'NO'"""
    )
    print(template)
    prompt = PromptTemplate.from_template(template)
    llm_chain = prompt | llm
    question = pregunta
    result = llm_chain.invoke(question)
    respuesta_llm = result.content
    return respuesta_llm

def filtro_coleccion(pregunta: str):
    DIRECCIONES_HORARIOS_OFICINAS = clasificacion(
        pregunta,
        "direcciones, ubicaciones u horarios de oficinas, agencias o sucursales",
    )
    print(DIRECCIONES_HORARIOS_OFICINAS)
    DIRECCIONES_JA_TIENDAS = clasificacion(
        pregunta,
        "direcciones o ubicaciones de ja tiendas o jardin azuayo tiendas",
    )
    DIRECCIONES_CORRESPONSALES = clasificacion(
        pregunta,
        "direcciones o ubicaciones de correspnsales",
    )
    DIRECCIONES_CAJEROS_AUTOMATICOS = clasificacion(
        pregunta,
        "direcciones o ubicaciones de cajeros automaticos o amts",
    )
    DIRECCIONES_Y_UBICACIONES = clasificacion(
        pregunta,
        "direcciones o ubicaciones en general",
    )
    DIRECTORIO_TELEFONICO_JARDIN_AZUAYO = clasificacion(
        pregunta,
        "ip o ips o nuemros de telefonos o directorio telefonico de oficinas, agencias o sucursales",
    )
    LISTADO_COLABORADORES_RESPONSABLES = clasificacion(
        pregunta,
        "responsables, gerentes o directores territoriales o tambien llamados territoriales de oficinas, agencias o sucursales",
    )
    NOMBRES_JARDIN_AZUAYO = clasificacion(
        pregunta,
        "nombres de personas",
    )
    REPRESENTANTES_COMITE_COORDINACION_GENERAL = clasificacion(
        pregunta,
        "comite de coordinacion general o representantes de comite de coordinacion general intregado por Gerente General,Gerente Administrativo Financiero,Gerente de Cultura Organizacional,Encargado de la Secretaría de Seguridad Integral,Gerente de Servicios Cooperativos,Director de Impulso a la Economía Solidaria,Director Servicios Administrativos,Director de Riesgos,Director de Tecnologías de Información,Dirección Fortalecimiento al Gobierno Cooperativo,Director Territorial Territorio Costa,Responsable Sucursal Territorio Loja,Unidad de Asesoría Territorio,Director Territorial Territorio Oriente,Unidad de Asesoría Territorio Norte, Responsable Sucursal Territorio El Oro",
    )
    INTEGRANTES_CONSEJO_VIGILANCIA = clasificacion(
        pregunta,
        "consejo de vigilancia o integrantes de consejo de vigilancia",
    )
    INTEGRANTES_CONSEJO_ADMINISTRACION = clasificacion(
        pregunta,
        "consejo de administracion o integrantes de consejo de administracion",
    )
    INTEGRANTES_COMISION_EDUCACION_COOPERATIVA = clasificacion(
        pregunta,
        "educacion cooperativa o integrantes de comision de educacion cooperativa",
    )
    INTEGRANTES_COMISION_CREDITO = clasificacion(
        pregunta,
        "comision de credito o integrantes de comision de credito",
    )
    INTEGRANTES_ASAMBLEA_LOCAL_SOCIOS = clasificacion(
        pregunta,
        "asamblea local de socios o integrantes de asamblea local de socios",
    )
    INTEGRANTES_ASAMBLEA_GENERAL_REPRESENTANTES = clasificacion(
        pregunta,
        "asamblea general de representantes o integrantes de asamblea general de representantes",
    )
    INTEGRANTES_ASAMBLEA_DELEGADOS_LOCALES = clasificacion(
        pregunta,
        "asamblea de delegados locales o integrantes de asamblea de delegados locales",
    )

    if "SI" in DIRECCIONES_HORARIOS_OFICINAS.upper():
        return milvus("DIRECCIONES_HORARIOS_OFICINAS")
    elif "SI" in DIRECCIONES_JA_TIENDAS.upper():
        return milvus("DIRECCIONES_JA_TIENDAS")
    elif "SI" in DIRECCIONES_CORRESPONSALES.upper():
        return milvus("DIRECCIONES_CORRESPONSALES")
    elif "SI" in DIRECCIONES_CAJEROS_AUTOMATICOS.upper():
        return milvus("DIRECCIONES_CAJEROS_AUTOMATICOS")
    elif "SI" in DIRECCIONES_Y_UBICACIONES.upper():
        return milvus("DIRECCIONES_Y_UBICACIONES")
    elif "SI" in DIRECTORIO_TELEFONICO_JARDIN_AZUAYO.upper():
        return milvus("DIRECTORIO_TELEFONICO_JARDIN_AZUAYO")
    elif "SI" in LISTADO_COLABORADORES_RESPONSABLES.upper():
        return milvus("LISTADO_COLABORADORES_RESPONSABLES")
    elif "SI" in NOMBRES_JARDIN_AZUAYO.upper():
        return milvus("NOMBRES_JARDIN_AZUAYO")
    elif "SI" in REPRESENTANTES_COMITE_COORDINACION_GENERAL.upper():
        return milvus("REPRESENTANTES_COMITE_COORDINACION_GENERAL")
    elif "SI" in INTEGRANTES_CONSEJO_VIGILANCIA.upper():
        return Milvus("INTEGRANTES_CONSEJO_VIGILANCIA")
    elif "SI" in INTEGRANTES_CONSEJO_ADMINISTRACION.upper():
        return milvus("INTEGRANTES_CONSEJO_ADMINISTRACION")
    elif "SI" in INTEGRANTES_COMISION_EDUCACION_COOPERATIVA.upper():
        return milvus("INTEGRANTES_COMISION_EDUCACION_COOPERATIVA")
    elif "SI" in INTEGRANTES_COMISION_CREDITO.upper():
        return milvus("INTEGRANTES_COMISION_CREDITO")
    elif "SI" in INTEGRANTES_ASAMBLEA_LOCAL_SOCIOS.upper():
        return milvus("INTEGRANTES_ASAMBLEA_LOCAL_SOCIOS")
    elif "SI" in INTEGRANTES_ASAMBLEA_GENERAL_REPRESENTANTES.upper():
        return milvus("INTEGRANTES_ASAMBLEA_GENERAL_REPRESENTANTES")
    elif "SI" in INTEGRANTES_ASAMBLEA_DELEGADOS_LOCALES.upper():
        return milvus("INTEGRANTES_ASAMBLEA_DELEGADOS_LOCALES")
    else:
        return milvus("INFORMACION_GENERAL")