"""Turn a spoken command into one function call.

The commands are real: utterances people spoke to a voice assistant, from the public MASSIVE data set (en-US test
split), each with the intent and the slots its annotators marked. Run it with `pip install openai`, then
`python tools-voice-commands.py`. The API is free and needs no key.
"""
# === setup ===
import json
import math
import re
from pathlib import Path

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

# === the tools ===
def tool(name, description, properties, required):
    return {"type": "function", "function": {"name": name, "description": description, "parameters": {
        "type": "object", "properties": properties, "required": required}}}


TOOLS = [
    tool("add_calendar_event", "Create something new on the user's calendar: an event, a meeting, or a reminder "
                               "(\"remind me to ...\", \"schedule ...\", \"add ... to my calendar\").",
         {"title": {"type": "string", "description": "What the event or the reminder is"},
          "date": {"type": "string", "description": "The day, as the user said it"},
          "time": {"type": "string", "description": "The time, as the user said it"},
          "place": {"type": "string", "description": "Where it is"}}, ["title"]),
    tool("get_calendar", "Look up what is already on the user's calendar: the schedule of a day, or when a meeting "
                         "or a reminder is.",
         {"date": {"type": "string", "description": "The day asked about, as the user said it"},
          "event": {"type": "string", "description": "The event asked about"}}, []),
    tool("get_date_time", "Tell what time or what date it is now, here or in another place. Only for the clock and "
                          "today's date.",
         {"place": {"type": "string", "description": "The place or time zone asked about"}}, []),
    tool("check_email", "Look at the emails the user has received: new mail, or mail from someone.",
         {"sender": {"type": "string", "description": "Whose emails to look for"}}, []),
    tool("send_email", "Write an email or a reply and send it.",
         {"to": {"type": "string", "description": "Who the email goes to, as the user said it"},
          "message": {"type": "string", "description": "What the email should say"}}, ["to"]),
    tool("get_weather", "The weather now or the forecast: temperature, rain, what to wear outside.",
         {"place": {"type": "string", "description": "The place asked about"},
          "date": {"type": "string", "description": "The day asked about, as the user said it"}}, []),
    tool("get_news", "News and headlines from papers, channels and news sites.",
         {"topic": {"type": "string", "description": "What the news should be about"},
          "source": {"type": "string", "description": "The paper, channel or site to take it from"}}, []),
    tool("play_music", "Play a song, an artist, an album, a genre or a playlist.",
         {"query": {"type": "string", "description": "What to play, as the user said it"}}, []),
    tool("post_to_social_media", "Post, tweet or publish a message or a complaint on a social network such as "
                                 "twitter or facebook.",
         {"network": {"type": "string", "description": "The network, such as twitter or facebook"},
          "text": {"type": "string", "description": "What to post"}}, ["text"]),
    tool("find_recipe", "Find how to cook or prepare a dish.",
         {"dish": {"type": "string", "description": "The dish or the ingredient"}}, ["dish"]),
    tool("no_matching_tool", "Call this for everything else: small talk, a question about a fact, a person or a "
                             "place, or a request that none of the other tools can do.",
         {"reason": {"type": "string", "description": "One sentence on why no tool fits"}}, ["reason"]),
]


def command_to_call(command):
    """(tool name, arguments) for one spoken command. `tool_choice="required"` makes the model call a tool."""
    reply = client.chat.completions.create(model="nenya", messages=[{"role": "user", "content": command}],
                                           tools=TOOLS, tool_choice="required")
    call = reply.choices[0].message.tool_calls[0]
    return call.function.name, json.loads(call.function.arguments)

# === the data ===
DATA = json.loads((Path(__file__).parent / "data" / "tools-voice-commands.json").read_text())

for t in TOOLS:
    print(f"{t['function']['name']}({', '.join(t['function']['parameters']['properties'])})")

# === the request ===
command = DATA["examples"][0]
name, arguments = command_to_call(command["text"])
print(f"command:    {command['text']}")
print(f"call:       {name}({json.dumps(arguments)})")
print(f"annotators: {command['annotated']}")

# === six commands ===
for command in DATA["examples"]:
    name, arguments = command_to_call(command["text"])
    print(f"{command['text']:<50} -> {name}({json.dumps(arguments)})")

# === where one request goes wrong ===
sample = DATA["sample"]                     # 60 commands, taken without looking at the answers
calls = [command_to_call(command["text"]) for command in sample]

right = sum(name == command["tool"] for (name, _), command in zip(calls, sample))
print(f"the right tool for {right} of {len(sample)} commands")
for t in TOOLS:
    mine = [name for (name, _), command in zip(calls, sample) if command["tool"] == t["function"]["name"]]
    print(f"{t['function']['name']:<22} {mine.count(t['function']['name']):2d} of {len(mine):2d}")

# === route, then extract ===
def classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
    """(label, confidence)"""
    options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
    prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
    if allow_none:
        prompt += ' If none of the options fits, answer "none".'
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=24,
        logprobs=True,                      # for the confidence
        extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
    )
    choice = reply.choices[0]
    tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
    confidence = math.exp(sum(t.logprob for t in tokens))
    return choice.message.content, confidence


def extract(kind, document, fields, max_tokens=800):
    """{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
    lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
    system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
              f"Fields:\n{lines}\n\n"
              "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
    properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
    schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
              "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=max_tokens,
        response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
    )
    choice = reply.choices[0]
    if choice.finish_reason != "stop":      # "length": the JSON was cut off and will not parse
        raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
    return json.loads(choice.message.content)


QUESTION = "Which intent does this voice-assistant command express?"
TOOL_FOR = DATA["tool_for"]                 # which tool answers which intent: {"check weather": "get_weather", ...}
INTENTS = sorted(TOOL_FOR)
BY_NAME = {t["function"]["name"]: t for t in TOOLS}


def route_then_extract(command):
    """(tool name, arguments). The intent as a classification, then the arguments as a JSON extraction whose
    fields are the tool's parameters. A parameter the command does not give comes back null and is left out."""
    intent, confidence = classify(QUESTION, command, INTENTS, heading="Command")
    name = TOOL_FOR[intent]
    if name == "no_matching_tool":
        return name, {"reason": f"the command is a {intent}"}
    parameters = BY_NAME[name]["function"]["parameters"]["properties"]
    fields = [{"name": key, "type": spec["type"], "description": spec["description"]} for key, spec in parameters.items()]
    record = extract("voice command", command, fields, max_tokens=200)
    return name, {key: value for key, value in record.items() if value is not None}


for command in DATA["examples"] + DATA["nothing_fits"]:
    name, arguments = route_then_extract(command["text"])
    print(f"{command['text']:<50} -> {name}({json.dumps(arguments)})")

# === keep what the user said ===
def said(value, command):
    """Is this value made of the user's own words? Every word of it has to be in the command."""
    words = re.findall(r"[a-z0-9']+", str(value).lower())
    return bool(words) and all(word in command.lower() for word in words)


def keep_what_was_said(arguments, command, copied=("date", "time")):
    """The call without the days and times the user did not say."""
    return {key: value for key, value in arguments.items() if key not in copied or said(value, command)}


for command in DATA["made_up"]:
    name, arguments = route_then_extract(command["text"])
    print(f"command:         {command['text']}")
    print(f"the model's call: {name}({json.dumps(arguments)})")
    print(f"after the check:  {name}({json.dumps(keep_what_was_said(arguments, command['text']))})")

# === measure it ===
routed = [route_then_extract(command["text"]) for command in sample]
right = sum(name == command["tool"] for (name, _), command in zip(routed, sample))
print(f"the right tool for {right} of {len(sample)} commands")
for t in TOOLS:
    mine = [name for (name, _), command in zip(routed, sample) if command["tool"] == t["function"]["name"]]
    print(f"{t['function']['name']:<22} {mine.count(t['function']['name']):2d} of {len(mine):2d}")
