
import os
import json
from datetime import datetime
from langchain_groq import ChatGroq
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, ToolMessage
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool

# Set the path so it can import from services
import sys
import os
sys.path.append(os.getcwd())

from config import get_settings
from services.chat_agent import SerpApi_Search, mcq_scenarios

def test_agent_scenario():
    settings = get_settings()
    llm = ChatGroq(
        api_key=settings.GROQ_API_KEY,
        model_name=settings.GROQ_MODEL,
        temperature=0.7,
    )
    
    today = datetime.now().strftime("%Y-%m-%d")
    system_prompt_str = f"""Role: Expert Investment Advisor AI for markets, strategy, and portfolio education.

1. INVESTMENT ADVICE & REAL-TIME DATA
Tool: Use SerpApi_Search for all news, current prices (e.g., Gold in Egypt), and market data.
Date: Today is {today}.

2. MCQ GENERATION (Practice)
**. SCENARIO PRESENTATION (UI/UX):**
When a scenario is retrieved, present it with high readability using this exact structure:
---
### 📊 Investment Case Study
> [Insert a concise, professional paragraph describing the situation.]

**Key Market Data:**
* 💵 **Initial Capital:** [Value]
* 📈 **Asset Class:** [Type]
* ⏱️ **Time Horizon:** [Duration]
* ⚠️ **Risk Level:** [Rating]

**Select the Best Course of Action:**
* **A)** [Option A text]
* **B)** [Option B text]
* **C)** [Option C text]
* **D)** [Option D text]
---
*Instruction: Wait for the user's letter (A-D) before providing the rationale.*

3. MCQ SCENARIO QUESTIONS (Database)
Tool: Use mcq_scenarios."""
    
    tools = [SerpApi_Search, mcq_scenarios]
    agent_executor = create_react_agent(llm, tools, prompt=system_prompt_str)
    
    user_message = "provide a scenario"
    print(f"User: {user_message}")
    
    response = agent_executor.invoke({
        "messages": [HumanMessage(content=user_message)]
    })
    
    messages = response["messages"]
    for i, msg in enumerate(messages):
        print(f"\n--- Message {i} ({type(msg).__name__}) ---")
        try:
            print(f"Content: {msg.content}")
        except UnicodeEncodeError:
            print(f"Content (UTF-8 bytes): {msg.content.encode('utf-8')}")
            
        if hasattr(msg, 'tool_calls'):
            print(f"Tool Calls: {msg.tool_calls}")

    last_msg = messages[-1]
    try:
        print(f"\nFinal Answer: '{last_msg.content}'")
    except UnicodeEncodeError:
        print(f"\nFinal Answer (UTF-8 bytes): '{last_msg.content.encode('utf-8')}'")

if __name__ == "__main__":
    test_agent_scenario()
