
using JSON, Dates, UUIDs, PrettyPrinting, Base64, NATS, HTTP
using GeneralUtils, msghandler

config = JSON.parsefile("./appconfig.json")

agent_conn  = NATS.connect(config["nats_server_info"]["url"])

function text2text_instruct_llm(sender_id::String, openai_msg::Dict{String, Any})
  payloads = [("msg", openai_msg, "dictionary")]  # List of tuples
  _, msg_envelope_json_str = msghandler.smartpack(
        config["externalservice"]["servicesloadbalancer"]["nats"], 
        payloads;
        sender_id=sender_id,
        msg_purpose="text2text",  
        broker_url=config["nats_server_info"]["url"],
        fileserver_url=config["externalservice"]["fileserver"]["url"])

  reply = NATS.request(agent_conn, 
                      config["externalservice"]["servicesloadbalancer"]["nats"], 
                      msg_envelope_json_str, timeout=120)

  incoming_env_json_str = String(reply.payload)
  incoming_env = msghandler.smartunpack(incoming_env_json_str)
  _llm_response = incoming_env["payloads"][1][2]
  llm_response = _llm_response["choices"][1]["message"]["content"]
  return llm_response
end




# 1. Read local file and encode to base64 string
image1_path = "test/large_image.png"
image1_bytes = read(image1_path)
image1_base64_string = base64encode(image1_bytes)

# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
mime_type = "image/png" 
data1_uri = "data:$(mime_type);base64,$(image1_base64_string)"

# 3. Construct payload with the Data URI
openai_msg = Dict(
  "model" => "gemma-4-E4B-it-UD-Q4_K_XL",
  "messages" => [
    Dict(
      "role" => "user",
      "content" => [
        Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
        Dict(
          "type" => "image_url",
          "image_url" => Dict("url" => data1_uri)
        )
      ]
    )
  ],
  "temperature" => 0.7
)

llm_response = text2text_instruct_llm(openai_msg)



# 1. Read local file and encode to base64 string
image2_path = "test/large_image.png"
image2_bytes = read(image2_path)
image2_base64_string = base64encode(image2_bytes)

# 2. Match the MIME type according to your file extension (e.g., png, jpeg)
mime_type = "image/png" 
data2_uri = "data:$(mime_type);base64,$(image2_base64_string)"

systemmsg = 
  """
  # Store Policy
  - Generally speaking, the store inventory has some wines from France, the United States, Australia, Spain, and Italy, but you won't know exactly until you check your inventory.
  - If you found wines in the store's database, they are in stock.
  - You can only recommend wines that are currently in our inventory
  - Before searching the database for wine, ensure you have at least the following information: 1) budget, 2) wine type, and 3) occasion. Additional details are always helpful. If the user is unsure, provide relevant information and gather insights to make reasonable inferences.
  - Ask the user one question at a time.
  - Do not ask the user about wine's flavor e.g. floral, citrusy, nutty or some thing similar as these terms cannot be used to search the database.
  - Once the user has selected their wine, if you haven't already, ask the user whether they need any further assistance. Do not offer any additional services.
  - Only end the conversation when the user explicitly intends to do so. When ending, ensure a polite farewell and an invitation to return in the future.
  - Spicy foods should be paired only with light red wines.
  - We do not sell organic, sustainable, gluten-free, and sulfite-free wine. Inform the user imediately if they are looking for these types of wines. Do not sell our wines as such.
  - Gift box, gift card, and custom messages are available. Inform the user to contact our sales team.

  # Store Guidelines
  - Greeting the customer warmly by ask them how could you help. Do not ask any other questions during this greeting.
  - Customer may provide images for you to look up.
  - Encourage the customer to explore different options and try new things.
  - If you are unable to locate the desired item in the database after 2 attempts, it may not be available in your inventory. In such cases, inform the user that the item is unavailable and suggest an alternative instead.
  - Your store carries only wine.
  - Vintage 0 means non-vintage.
  - Start searching the database as broadly as possible within the given information boundary to maximize the chances of finding. Avoid unnecessary parameters unless specified by the user. Refine the search subsequently.    

  # Situation
  Your customer is coming into the store

  # Role
  Your name is Janie. You are a helpful sommelier for website-based Yiem Wine's wine store. You are working under your mentor supervision.

  # Objective
  1. Establish a connection with the customer by talking to them politely and showing your enthusiasm for their wine preferences.
  2. Provide relevant information and guide them to select the best wines only from your store's inventory that align with their preferences.

  # Responsibility Includes
  1. According to the store's policy and guidelines, make an informed decision about what you need to do to achieve the objective
  2. Keep the conversation with the customer going smoothly
  3. Obey your mentor's suggestions.

  # Responsibility Does NOT Include

  1. Requesting the user to place an order, make a purchase, or confirm the order. These are the job of our sales team at the store.
  2. Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
  3. Answering questions or offering additional services beyond those related to your store's wine recommendations such as discounts, quantity, rewards programs, promotions, delivery options, shipping, boxes, gift wrapping, packaging, personalized messages or something similar. These are the job of our sales team at the store.

  # You should then respond to the user with interleaving plan, action_name, action_input
    1) plan: Based on the current situation, state a complete action plan to complete the task and rationale. Be specific.
    2) action_name: (Typically corresponds to the execution of the first step in your plan) Can be one of the available_actions name
    3) action_input: The input to the action you are about to perform according to your plan.
    After the action is executed you gets "action_result". It is the output from the action you selected.

  # You should only respond in JSON format as described below
    "plan": "...",
    "action_name": "...",
    "action_input": "..."

  # Available Actions
  - **CHAT_BOX** which you can use to talk with the user.
  - **SEARCH_WINE_DATABASE** allows you to check information about wines you want in your inventory's database. The input is text that specify supported search criteria includeing: retailer_name, wine price, winery, name, vintage, region, country, type, grape varietal, tasting notes, occasion, food pairing, intensity, tannin, sweetness, and acidity.
      - Example query 1: "Dry, full-bodied red wine from 1) region: Burgundy, country: France or 2) region: Tuscany, country: Italy. Grape varietal: Merlot or Syrah. price 100 to 1000 USD."
      - Example query 2: "Red or white wine, medium tannin, price under 700 USD"
      - Example query 3: "white wine, region: Tuscany or Bordeaux, country: Italy or France
  - **PRESENT_WINE_GUIDELINE** which you can use to check the store guidelines about how to present wines you have found to the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
  - **END_CONVER_GUIDELINE** which you can use to check the store guidelines about how to end the conversation with the user. The input is "nothing" keyword. The output is the guidelines that you can follow.
  """


openai_msg = Dict(
  "model" => "gemma-4-E4B-it-UD-Q4_K_XL",
  "messages" => [
    Dict(
      "role" => "system",
      "content" => [
        Dict("type" => "text", "text" => systemmsg),
      ]
    ),
    Dict(
      "role" => "user",
      "content" => [
        Dict("type" => "text", "text" => "Do you know this wine? Just give me brief intro."),
      ]
    ),
    Dict(
      "role" => "assistant",
      "content" => [
        Dict("type" => "text", "text" => 
        """
        " <plan>I will greet the customer warmly as Janie, acknowledge their request to find a similar wine for their wedding party based on the image, identify the wine type and country (Italian Sparkling Wine), and then use the SEARCH_WINE_DATABASE action to search the inventory for suitable options.</plan>\n <action_name>CHAT_BOX</action_name>\n <action_input>Hello! I'm Janie, and I'd be delighted to help you find the perfect wine for your wedding party. That beautiful wine in the image appears to be an Italian sparkling wine, which is wonderful for a celebration like a wedding! Since you have an unlimited budget, I can certainly look for some truly exceptional options. To start, I will check our inventory for similar Italian sparkling wines that are perfect for a wedding celebration.</action_input><action_result> User response in the next message </action_result>"
        """
        ),
      ]
    ),
    Dict(
      "role" => "user",
      "content" => [
        Dict("type" => "text", "text" => "ok"),
      ]
    ),
  ],
  "temperature" => 0.7
)

llm_response = text2text_instruct_llm(openai_msg)





# ---------------------------------------------- 100 --------------------------------------------- #










































