export function parseLog(
  log: string,
): Record<string, object | string | number> {
  const logArray = log
    .split("\\n")
    .map((line) => line.trim())
    .filter((line) => line);

  const jsonObject: Record<string, object | string | number> = {};
  let currentSection: Record<string, object | string | number> = jsonObject;
  const sectionStack: Record<string, object | string | number>[] = [];

  logArray.forEach((line) => {
    line = line.trim();

    if (line.startsWith("->")) {
      const match = line.match(/->\s+([^:]+):\s+(Str|Int)\((.+)\)/);
      if (match) {
        const [, key, type, value] = match;
        const parsedValue = type === "Int" ? parseInt(value, 10) : value;

        if (typeof currentSection === "object") {
          currentSection[key] = parsedValue;
        }
      }
    } else if (line.endsWith(":")) {
      // new section
      const sectionName = line
        .slice(0, -1)
        .trim()
        .toLowerCase()
        .replace(" ", "_");
      jsonObject[sectionName] = {};
      currentSection = jsonObject[sectionName] as Record<
        string,
        object | string | number
      >;
      sectionStack.push(currentSection);
    } else if (line.startsWith('"')) {
      // Additional metadata at the end, store it separately
      jsonObject["metadata"] = line;
    }

    if (line.includes("Body:")) {
      const match = line.match(/Body:\s+(\w+)\((.+)\)/);
      if (match) {
        jsonObject["log_body"] = match[2];
      }
    }
  });

  return jsonObject;
}
