# """
# LangChain-powered chatbot for warehouse inventory queries
# """
# import pandas as pd
# from typing import List, Dict, Any
# from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
# from langchain_groq import ChatGroq
# import streamlit as st
# import sys, os
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# from api_client import WarehouseAPI

# class WarehouseChatbot:
#     """
#     AI-powered chatbot for answering warehouse inventory questions
#     using LangChain and Groq (FREE)
#     """
    
#     def __init__(self, api_key: str = None):
#         """
#         Initialize the chatbot with Groq via LangChain
        
#         Args:
#             api_key: Groq API key (or set GROQ_API_KEY env var)
#         """
#         self.api_key = api_key or os.getenv("GROQ_API_KEY")
        
    
#         self.llm = ChatGroq(
#             # model="llama-3.3-70b-versatile", 
#          model="llama-3.3-70b-versatile",
#             groq_api_key=self.api_key,
#             temperature=0.3,
#             max_tokens=1024
#         )
        
#         # Load warehouse data
#         # self.order_items_df = None
#         # self.inventory_df = None
#         # self.skus_df = None
#         # self.load_data()
        
#         # Conversation history
#         self.chat_history = []
        
#     # def load_data(self):
#     #     """Load warehouse data from CSVs"""
#     #     try:
#     #         self.order_items_df = pd.read_csv('app/data/orders_for_forecast.csv')
#     #         self.inventory_df = pd.read_csv('app/data/inventory.csv')
#     #         self.skus_df = pd.read_csv('app/data/skus.csv')
#     #     except Exception as e:
#     #         print(f"Warning: Could not load data files: {e}")
    
#     @st.cache_data
#     def load_data():
#         api = WarehouseAPI()
#         try:
#             inventory_df = api.get_inventory()
#             order_items_df = api.get_order_items()
#             orders_df = api.get_orders()
#             product_df = api.get_products()
#             spare_parts_df = api.get_spare_parts()
#             warehouses_df = api.get_warehouses()
#             return inventory_df, order_items_df, product_df, spare_parts_df, warehouses_df, orders_df

#         except Exception as e:
#             st.error("API load error")
#             return pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame()

#     #inventory = pd.read_csv("mock_inventory.csv")
#     #orders = pd.read_csv("mock_orders.csv")
#     #product = pd.read_csv("mock_products.csv")
#     #spare_parts = pd.read_csv("mock_spare_parts.csv")
#     #warehouses = pd.read_csv("mock_warehouses.csv")

#     # return inventory, orders, product, spare_parts, warehouses


#     # -----------------------------
#     # Load all data
#     # -----------------------------
#     inventory_df, order_items_df, product_df, spare_parts_df, warehouses_df, orders_df = load_data()
    
#     def get_data_context(self) -> str:
#         """Generate context about available data"""
#         context_parts = []
        
#         if self.order_items_df is not None:
#             total_orders = len(self.order_items_df)
#             unique_skus = self.order_items_df['sku'].nunique()
#             date_range = f"{self.order_items_df['order_date'].min()} to {self.order_items_df['order_date'].max()}"
#             context_parts.append(
#                 f"Orders Data: {total_orders:,} total orders, {unique_skus} unique SKUs, "
#                 f"date range: {date_range}"
#             )
            
#             # Top SKUs
#             top_skus = self.order_items_df.groupby('sku')['qty'].sum().nlargest(5)
#             context_parts.append(f"Top 5 SKUs by volume: {', '.join(top_skus.index.tolist())}")
        
        
        
        
#         #------------------------ NEEDS REVIEW -------------
        
        
#         # if self.inventory_df is not None:
#         #     context_parts.append(f"Inventory Data: {len(self.inventory_df)} items tracked")
        
#         # if self.skus_df is not None:
#         #     context_parts.append(f"SKU Master Data: {len(self.skus_df)} SKUs in catalog")
        
        
#         #-----------------------------------------------------
        
#         return "\n".join(context_parts)
    
#     def analyze_query(self, query: str) -> Dict[str, Any]:
#         """
#         Analyze the query to extract relevant data
#         Returns structured data that can help answer the question
#         """
#         analysis = {
#             'query_type': None,
#             'data': None,
#             'insights': []
#         }
        
#         query_lower = query.lower()
        
#         # Detect query type and fetch relevant data
#         if any(word in query_lower for word in ['order', 'orders', 'sales']):
#             analysis['query_type'] = 'orders'
#             if self.order_items_df is not None:
#                 # Recent orders summary
#                 recent = self.order_items_df.tail(10)
#                 analysis['data'] = recent.to_dict('records')
#                 analysis['insights'].append(f"Found {len(self.order_items_df)} total orders")
        
#         elif any(word in query_lower for word in ['inventory', 'stock', 'quantity']):
#             analysis['query_type'] = 'inventory'
#             if self.inventory_df is not None:
#                 analysis['data'] = self.inventory_df.to_dict('records')
#                 analysis['insights'].append(f"Tracking {len(self.inventory_df)} inventory items")
        
#         elif any(word in query_lower for word in ['sku', 'product']):
#             analysis['query_type'] = 'sku'
#             # Extract SKU if mentioned
#             for word in query.split():
#                 if 'SKU-' in word.upper():
#                     sku = word.upper()
#                     if self.order_items_df is not None:
#                         sku_orders = self.order_items_df[self.order_items_df['sku'] == sku]
#                         if not sku_orders.empty:
#                             total_qty = sku_orders['qty'].sum()
#                             analysis['data'] = {
#                                 'sku': sku,
#                                 'total_quantity': int(total_qty),
#                                 'order_count': len(sku_orders),
#                                 'recent_orders': sku_orders.tail(5).to_dict('records')
#                             }
#                             analysis['insights'].append(
#                                 f"SKU {sku}: {total_qty} units ordered across {len(sku_orders)} orders"
#                             )
        
#         elif any(word in query_lower for word in ['top', 'best', 'most', 'popular']):
#             analysis['query_type'] = 'top_items'
#             if self.order_items_df is not None:
#                 top_skus = self.order_items_df.groupby('sku')['qty'].agg(['sum', 'count']).nlargest(10, 'sum')
#                 analysis['data'] = top_skus.to_dict('index')
#                 analysis['insights'].append(f"Top 10 SKUs by order volume")
        
#         return analysis
    
#     def chat(self, user_message: str) -> str:
#         """
#         Process a user message and return AI response
        
#         Args:
#             user_message: The user's question
            
#         Returns:
#             AI-generated response
#         """
#         # Analyze the query
#         analysis = self.analyze_query(user_message)
        
#         # Build system prompt with warehouse context
#         system_prompt = f"""You are an intelligent warehouse management assistant. You help warehouse managers 
# understand their inventory, orders, and operations.

# Available Warehouse Data:
# {self.get_data_context()}

# Query Analysis:
# Type: {analysis['query_type']}
# Insights: {', '.join(analysis['insights']) if analysis['insights'] else 'None'}

# Guidelines:
# - Be concise and helpful
# - Use specific numbers and data when available
# - If you don't have the exact data, say so and suggest alternatives
# - Focus on actionable insights
# - Use bullet points for clarity when listing items

# Current Query Data:
# {str(analysis['data'])[:500] if analysis['data'] else 'No specific data extracted'}
# """
        
#         # Build message chain
#         messages = [SystemMessage(content=system_prompt)]
        
#         # Add chat history (last 5 messages for context)
#         for msg in self.chat_history[-5:]:
#             if msg['role'] == 'user':
#                 messages.append(HumanMessage(content=msg['content']))
#             else:
#                 messages.append(AIMessage(content=msg['content']))
        
#         # Add current message
#         messages.append(HumanMessage(content=user_message))
        
#         # Get response from Claude
#         response = self.llm.invoke(messages)
        
#         # Update chat history
#         self.chat_history.append({'role': 'user', 'content': user_message})
#         self.chat_history.append({'role': 'assistant', 'content': response.content})
        
#         return response.content
    
#     def clear_history(self):
#         """Clear conversation history"""
#         self.chat_history = []


# # Example usage
# if __name__ == "__main__":
#     # Initialize chatbot (requires ANTHROPIC_API_KEY env var)
#     chatbot = WarehouseChatbot()
    
#     # Example queries
#     queries = [
#         "How many total orders do we have?",
#         "What are our top selling SKUs?",
#         "Tell me about recent order trends"
#     ]
    
#     for query in queries:
#         print(f"\n🧑 User: {query}")
#         response = chatbot.chat(query)
#         print(f"🤖 Assistant: {response}")