import copy
import json
import re
from typing import Any, Dict, List


def language_action_to_subgoal(action, waypoint) -> str:
    subgoal = {
        "task": action,
        "goal": [waypoint, 1],
    }
    subgoal_str = json.dumps(subgoal)

    return subgoal, subgoal_str


def render_subgoal(subgoal: str, wp_num: int = 1) -> str:
    subgoal = subgoal.replace("<task planning>:", "<task planning>").replace("**", "")
    sep_str = "<task planning>"

    temp = subgoal.split(sep_str)[-1].strip()
    if "```json" in temp:
        temp = temp.split("```json")[1].strip().split("```")[0].strip()

    if "{{" in temp:
        temp = temp.replace("{{", "{").replace("}}", "}")

    r = temp.rfind("}")
    temp = temp[: r + 1]

    try:
        temp = json.loads(temp)
    except json.JSONDecodeError as e:
        return [], None, str(e)

    temp["goal"][1] = wp_num

    return temp, temp["task"], None

