# uuid=63e765ef-6c95-48a7-93b5-59fba59b7aea
# version=1

if version\0 < 1:

    from channels    import send_message_to_thread, wait_for_new_messages_on_thread, format_messages, User
    from core_skills import format_goal_stack, get_answer_to_question
    from llm         import agent

    type DietLogEntry:
        val when                                -- For now an ISO time string
        val when_text                           -- How the user initially described the time (e.g., "lunch")
        val items                               -- A list of items eaten

    type User:
        one diet_log                            -- We can monkey-patch new properties onto types rather than creating global maps.

    def diet_log(user):                         -- TODO: We need factory fields on types!
        if not user.diet_log?:
            user.diet_log = []
        return user.diet_log

    format_diet_log_entry = <e: "[{e.when}] ({e.when_text}) {sjoin(e.items, ', ')}">
    format_diet_log       = <l: joinlines([format_diet_log_entry(e) for e in l])>

    {|
     | Track what the user eats and drinks.
     |}
    def track_diet(thread, user):
        ate_what = get_answer_to_question(thread, "What did you eat and (roughly) when?",
            instructions="Be sure to list _everything_ the user mentioned eating in this thread,
                          even if at different times, and be sure to include the respective times!")
        print("The user ate: {ate_what}")
        items = agent($"The current goal stack is:
                            {format_goal_stack()}

                        Re-format "{ate_what}" as a json object mapping each time to a list of items consumed then.

                        Return action='itemize', items=<the mapping>, as in:

                        {{reason="...", action="itemize", items={{"lunch": ["turkey", "mashed potatoes"], "3pm": ["cookie"]}}
                        "$).items
        if not items?:
            send_message_to_thread(thread, "Sorry, having trouble today.  Let's start over from the beginning...")
            return

        for when:item_list in items:
            when_iso = get_answer_to_question(thread, "When, roughly, was {quote(when)}?",
                instructions="- Don't make guesses for when, e.g., 'dinner' is--just ask
                              - Conversely, don't pester!  Once you have an approximate time of day, that's good enough.
                              - Assume the user's timezone is as shown in the chat log timestamps.
                              - Convert their answer to ISO format in the same timezone before returning.
                              ")
            append(diet_log(user), DietLogEntry(when=when_iso, when_text=when, items=item_list))

        send_message_to_thread(thread,
            "Your diet log to date:
                {format_diet_log(user.diet_log)}
             ")