# user_journey_service/processors/user_journey_synthesizer.py
import os
import yaml
from pathlib import Path
from crewai import LLM
from user_journey_service.core.config import settings

# Define prompts path
prompts_path = Path(__file__).parent.parent / "config" / "prompts.yaml"

class Synthesizer:
    def __init__(self):
        # Get API key
        #api_key = os.getenv("OPENAI_API_KEY") or settings.OPENAI_API_KEY
        api_key=settings.OPENAI_KEY2,
        
        if not api_key:
            raise ValueError("OPENAI_API_KEY is required")
        
        # Use standard OpenAI configuration (remove Azure-specific parameters)
        self.llm = LLM(
            model=f"openai/{settings.LLM_FOR_REVIEW}",
            temperature=settings.TEMPERATURE,
            api_key=api_key,  # Use standard OpenAI key
            seed=settings.SEED,
            timeout=settings.TIMEOUT
            # REMOVED: api_version, api_base, etc.
        )
        
        # Load prompts
        self.prompts = self.load_prompts()
        
        print("✓ Synthesizer LLM initialized")

    def load_prompts(self):
        """Load prompts from YAML file"""
        try:
            if prompts_path.exists():
                with open(prompts_path, "r") as f:
                    return yaml.safe_load(f)
            else:
                print(f"⚠️ Prompts file not found at {prompts_path}, using defaults")
                return {
                    "user_journey_synthesizer": """
                    You are an expert product strategist and instructional designer.
                    Below are two user journeys generated for a user with the following profile:

                    Designation: {designation}
                    Skills: {skills}
                    Experience: {experience}

                    User Journey 1 :
                    {content1}
                    User Journey 2:
                    {content2}

                    Task:
                    Carefully compare both user journeys.
                    Identify overlaps, differences, strengths, and any missing elements based on the user's profile.
                    Combine them to create a single, refined, logically ordered, and practical combined user journey that is aligned to the given user profile.
                    Ensure the combined journey avoids redundancy, resolves conflicts, and integrates complementary steps effectively.

                    Output format:
                    Same as the already given user journey in markdown with stages
                    """
                }
        except Exception as e:
            print(f"⚠️ Error loading prompts: {e}, using defaults")
            return {
                "user_journey_synthesizer": """
                Combine these two user journeys for {designation} with {experience} experience and skills: {skills}
                Journey 1: {content1}
                Journey 2: {content2}
                Output: Combined journey in markdown format.
                """
            }

    def review_and_combine(self, designation, skills, experience, content1, content2):
        print("Inside synthesizer function....")
        
        # Get prompt template
        prompt_template = self.prompts.get("user_journey_synthesizer", 
            "Combine journeys for {designation}: {content1} and {content2}")
        
        prompt = prompt_template.format(
            designation=designation,
            experience=experience,
            skills=skills,
            content1=content1,
            content2=content2
        )
        
        print(f"Synthesizer prompt length: {len(prompt)} chars")
        
        # LLM message format
        messages = [{'role': 'user', 'content': prompt}]

        # Call the LLM
        response = self.llm.call(messages)
        
        print(f"Synthesizer response length: {len(response)} chars")
        
        return response