module type
  
export agent, sommelier, companion, virtualcustomer, agentcontext

using Dates, UUIDs, DataStructures, JSON, NATS
using GeneralUtils

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


mutable struct agentcontext
  text2textInstructLLM::Function
  getTextEmbedding::Function
  executeSQL::Function
  similarSQLVectorDB::Function
  insertSQLVectorDB::Function
  similarSommelierDecision::Function
  insertSommelierDecision::Function
  find_related_tables_for_user_question::Function
  pg_conn_str::String
  agentconfig::AbstractDict
end

abstract type agent end

mutable struct companion <: agent
  name::String  # agent name
  id::String    # agent id
  systemmsg::String # system message
  tools::Dict  # tools
  maxHistoryMsg::Integer  # e.g. 21th and earlier messages will get summarized
  chathistory::Vector{Dict{String, Any}}
  memory::Dict{String, Any}
  context::NamedTuple  # NamedTuple of functions 
  llmFormatName::String
end

function companion(
  context::agentcontext  # NamedTuple of functions
  ;
  name::String= "Assistant",
  id::String= GeneralUtils.uuid4snakecase(), 
  maxHistoryMsg::Integer= 20,
  chathistory::Vector{Dict{String, String}} = Vector{Dict{String, String}}(),
  llmFormatName::String= "granite3",
  systemmsg::String=
    """
      Your name: $name
      Your sex: Female
      Your role: You are a helpful assistant.
      You should follow the following guidelines:
      - Focus on the latest conversation.
      - Your like to be short and concise.

      Let's begin!
      """,
  )

  tools = Dict( # update input format
      "CHAT_BOX"=> Dict(
        "description" => "- CHAT_BOX which you can use to talk with the user. The input is your intentions for the dialogue. Be specific.",
      ),
    )

  """ Memory
    Ref: Chat prompt format https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/discussions/3
    NO "system" message in chathistory because I want to add it at the inference time
    chathistory= [
      Dict("name"=>"user", "text"=> "Wassup!", "timestamp"=> Dates.now()),
      Dict("name"=>"assistant", "text"=> "Hi I'm your assistant.", "timestamp"=> Dates.now()),
    ]
  """
  memory = Dict{String, Any}(
            "events"=> Vector{Dict{String, Any}}(),
            "state"=> Dict{String, Any}(), # state of the agent
            "recap"=> OrderedDict{String, Any}(),  # recap summary of the conversation
          )

  newAgent = companion(
    name,
    id,
    systemmsg,
    tools,
    maxHistoryMsg,
    chathistory,
    memory,
    context,
    llmFormatName
    )
  
  return newAgent
end


mutable struct sommelier <: agent
  name::String  # agent name
  id::String    # agent id
  retailername::String
  retailerid::String
  tools::Dict   
  maxHistoryMsg::Integer  # e.g. 21th and earlier messages will get summarized
  chathistory::Vector{Dict{String, Any}}
  memory::Dict{String, Any}
  context::agentcontext 
  llmFormatName::String
end
 
""" A sommelier agent.

# Arguments
  - `context::agentcontext`
    Application context containing shared functions for LLM, SQL, and vector database operations.

# Keyword Arguments
  - `name::String`
    Agent's name. Default: `"Assistant"`
  - `id::String`
    Agent's ID. Default: generated UUID string.
  - `retailername::String`
    Retailer name associated with the sommelier. Default: `"retailer_name"`
  - `maxHistoryMsg::Integer`
    Maximum history messages. Default: `20`
  - `chathistory::Vector{Dict{String, String}}`
    Chat history. Default: empty vector.
  - `llmFormatName::String`
    LLM format name. Default: `"granite3"`

# Return
  - `sommelier`: An instantiated sommelier agent.

# Example
```julia
julia> using YiemAgent
julia> context = agentcontext(
           text2textInstructLLM,
           getTextEmbedding,
           executeSQL,
           similarSQLVectorDB,
           insertSQLVectorDB,
           similarSommelierDecision,
           insertSommelierDecision
       )
julia> agent = sommelier(context, name="WineExpert", id="123", retailername="MyWineShop")
```
"""
function sommelier(
  context::agentcontext,  # agent functions, db connect and other context
  ;
  name::String= "Assistant",
  id::String= string(uuid4()),
  retailername::String= "not specified",
  retailerid::String= "not specified",
  maxHistoryMsg::Integer= 20,
  chathistory::Vector{Dict{String, Any}} = Vector{Dict{String, Any}}(),
  llmFormatName::String= "granite3"
  )

  tools = Dict( # update input format
      "chatbox"=> Dict(
        "description" => "<askbox tool description>Useful for when you need to ask the user for more context. Do not ask the user their own question.</askbox tool description>",
        "input" => """<input>Input is a text in JSON format.</input><input example>{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}</input example>""",
        "output" => "" ,
      ),
      "winestock"=> Dict(
        "description" => "<winestock tool description>A handy tool for searching wine in your inventory that match the user preferences.</winestock tool description>",
        "input" => """<input>Input is a JSON-formatted string that contains a detailed and precise search query.</input><input example>{\"wine type\": \"rose\", \"price\": \"max 35\", \"sweetness level\": \"sweet\", \"intensity level\": \"light bodied\", \"Tannin level\": \"low\", \"Acidity level\": \"low\"}</input example>""",
        "output" => """<output>Output are wines that match the search query in JSON format.""",
      ),
    )

  """ Memory

    Chat history use openai format as follow:

    image1_path = "test/large_image.png"                           ---
    image1_bytes = read(image1_path)                                 | this part must be done
    image1_base64_string = base64encode(image1_bytes)                | in frontend 
    mime_type = "image/png"                                          | not in agent code
    data1_uri = "data:<mime_type>;base64,<image1_base64_string>"   ---

    chathistory= [
      Dict(
        "role" => "system",
        "content" => [
          Dict("type" => "text", "text" => "You are a helpful assistant"),
        ]
      ),
      Dict(
        "role" => "user",
        "content" => [
          Dict("type" => "text", "text" => "<internal_context_for_assistant> 
                                            LLM context here...
                                            </internal_context_for_assistant>
                                            Do you know this wine? Just give me brief intro."
          ),
          Dict(
            "type" => "image_url",
            "image_url" => Dict("url" => data1_uri)
          ),
        ]
      ),
    ]
  
  shortmem = Dict(
    "1"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."),
    "2"=> Dict("plan"=> "...", "action_name"=> "...", "action_input"=> "...", "action_result"=> "..."),
    ...
    )
  """
  memory = Dict{String, Any}(
            "shortmem"=> OrderedDict{String, Any}(),
            "scratchpad"=> "",
            "events"=> Vector{Dict{String, Any}}(),
            "state"=> Dict{String, Any}(
            ),
            "recap"=> OrderedDict{String, Any}(),
            
          )

  newAgent = sommelier(
    name,
    id,
    retailername,
    retailerid,
    tools,
    maxHistoryMsg,
    chathistory,
    memory,
    context,
    llmFormatName
    )
  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
      You are having conversation with a customer.

    # your role
      Your name is $(newAgent.name). You are a helpful sommelier for website-based $(newAgent.retailername)'s wine store.

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

    # your responsibility includes
      - According to the store's policy and guidelines, and make an informed decision about what available_actions you need to use to achieve the objective.
      - Keep the conversation with the customer going smoothly

    # your responsibility does NOT includes
      - 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.
      - Processing sales orders or engaging in any other sales-related activities. These are the job of our sales team at the store.
      - 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 (not Markdown format)
      "plan": "...",
      "action_name": "...",
      "action_input": "..."

    # available actions
      "CHAT_BOX", which you can use to talk with the user. The input is dialogue you want to chat with the user according to your plan.
      "SEARCH_WINE_DATABASE", allows you to search information about wines you want in your inventory's database. The input is supported search criteria including: 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
      "WINE_PRESENTATION_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.
    """
    
  system_msg = Dict(
      "role" => "system",
      "content" => [
        Dict("type" => "text", "text" => systemmsg),
      ]
    )

  push!(newAgent.chathistory, system_msg)
  
  return newAgent
end


mutable struct virtualcustomer <: agent
  name::String  # agent name
  id::String    # agent id
  systemmsg::String # system message
  tools::Dict   
  maxHistoryMsg::Integer  # e.g. 21th and earlier messages will get summarized
  chathistory::Vector{Dict{String, Any}}
  memory::Dict{String, Any}
  context  # NamedTuple of functions 
  llmFormatName::String
end

function virtualcustomer(
  context,  # NamedTuple of functions
  ;
  name::String= "Assistant",
  id::String= string(uuid4()),
  maxHistoryMsg::Integer= 20,
  chathistory::Vector{Dict{String, String}} = Vector{Dict{String, String}}(),
  llmFormatName::String= "granite3",
  systemmsg::String=
    """
      Your name: $name
      Your sex: Female
      Your role: You are a helpful assistant.
      You should follow the following guidelines:
      - Focus on the latest conversation.
      - Your like to be short and concise.

      Let's begin!
      """,
  )

  tools = Dict( # update input format
      "chatbox"=> Dict(
        "description" => "<askbox tool description>Useful for when you need to ask the user for more context. Do not ask the user their own question.</askbox tool description>",
        "input" => """<input>Input is a text in JSON format.</input><input example>{\"Q1\": \"How are you doing?\", \"Q2\": \"How may I help you?\"}</input example>""",
        "output" => "" ,
      ),
    )

  """ Memory
    Ref: Chat prompt format is openai
    chathistory = [
      Dict(
        "role" => "system",
        "content" => [
          Dict("type" => "text", "text" => system_msg),
        ]
      ),
      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)
          )
        ]
      )
    ]
  """
  memory = Dict{String, Any}(
            "shortmem"=> OrderedDict{String, Any}(
            ),
            "scratchpad"=> "",
            "events"=> Vector{Dict{String, Any}}(),
            "state"=> Dict{String, Any}(
            ),
            "recap"=> OrderedDict{String, Any}(),
          )

  newAgent = virtualcustomer(
    name,
    id,
    systemmsg,
    tools,
    maxHistoryMsg,
    chathistory,
    memory,
    context,
    llmFormatName
    )
  
  return newAgent
end


























































end # module type