#!/usr/bin/env python

import argparse
import os
from datetime import datetime

from synthetic_agents.app.playable_chat import PlayableChat

parser = argparse.ArgumentParser(
    description="Plays a chat between a user and a coach agent. The chat will play and messages "
                "will be persisted to the database as in the online chat. There's also an option "
                "to export the chat to a CSV file at the end."
)
parser.add_argument(
    "--chat_id",
    type=int,
    required=True,
    help="ID of the chat to be played.",
)
parser.add_argument(
    "--n_messages",
    type=int,
    required=False,
    default=10,
    help="Maximum number of messages to be exchanged between the agents.",
)
parser.add_argument(
    "--save_to_csv",
    type=int,
    required=False,
    default=0,
    help="Whether to save the messages to CSV in the end of the chat.",
)
parser.add_argument(
    "--csv_out_dir",
    type=str,
    required=False,
    help="Directory where the CSV file must be saved if the option `save_to_csv` is set to True.",
)

args = parser.parse_args()
chat = PlayableChat(chat_id=args.chat_id)
chat.initialize_chat()
chat.play(number_messages=args.n_messages)

if args.save_to_csv:
    if args.csv_out_dir is None:
        raise Exception(f"`save_to_csv` was set to True but `csv_out_dir` was not given.")

    run_id = datetime.now().strftime("%Y.%m.%d--%H.%M.%S")
    timestamped_filename = f"chat_{chat.chat_id}_{run_id}.csv"
    chat.export_to_csv(out_dir=args.csv_out_dir, filename=timestamped_filename)
