import os
from langchain_openai import ChatOpenAI
from langchain_community.chat_models import ChatOllama
from langchain.prompts import ChatPromptTemplate

class AIAgentService:
    def __init__(self):
        self.default_model_type = os.getenv("DEFAULT_AI_PROVIDER", "openai")
        
        # Initialize providers
        self.openai_llm = ChatOpenAI(temperature=0.7, model_name="gpt-4-turbo")
        self.ollama_llm = ChatOllama(model="llama3", temperature=0.7)

    async def process_request(self, email_context: str, instruction: str, mode: str):
        llm = self.openai_llm if self.default_model_type == "openai" else self.ollama_llm
        
        # System Prompt Tuning based on Mode
        system_prompt = "You are a highly professional enterprise Outlook AI Assistant."
        
        if mode == "professional":
            system_prompt += " Generate a highly professional and formal reply."
        elif mode == "concise":
            system_prompt += " Generate a very short, direct, and concise reply. No fluff."
        elif mode == "support":
            system_prompt += " Generate a polite, empathetic, and helpful customer support reply."
        elif mode == "summarize":
            system_prompt += " Provide a short, bulleted summary of the core points of the email thread."
        else:
            system_prompt += " Follow the user's instructions carefully."

        prompt_template = ChatPromptTemplate.from_messages([
            ("system", system_prompt),
            ("human", "Email Context:\n{context}\n\nInstruction:\n{instruction}")
        ])

        chain = prompt_template | llm
        
        response = chain.invoke({
            "context": email_context,
            "instruction": instruction
        })
        
        return {
            "text": response.content,
            "model": self.default_model_type
        }
