# -*- coding: utf-8 -*-
import gdb
import json
import csv


def extract_vector(var):
    start = var["_M_impl"]["_M_start"]
    finish = var["_M_impl"]["_M_finish"]
    size = int(finish - start)
    result = []
    for i in range(size):
        item = start[i]
        id_ = int(item["id"])
        value = float(item["value"])

        # Estrazione compatibile del nome (stringa C++11)
        name_obj = item["name"]
        try:
            name_ptr = name_obj["_M_dataplus"]["_M_p"]
            name = name_ptr.string()
        except:
            name = "<error>"

        result.append({"id": id_, "name": name, "value": value})
    return result


class DumpToJson(gdb.Command):
    """Dump a std::vector<MyData> to JSON."""

    def __init__(self):
        gdb.Command.__init__(self, "dump_to_json", gdb.COMMAND_USER)

    def invoke(self, arg, from_tty):
        var = gdb.parse_and_eval(arg)
        data = extract_vector(var)
        with open("output.json", "w") as f:
            json.dump(data, f, indent=4)
        print("JSON written with {} entries.".format(len(data)))


class DumpToCsv(gdb.Command):
    """Dump a std::vector<MyData> to CSV."""

    def __init__(self):
        gdb.Command.__init__(self, "dump_to_csv", gdb.COMMAND_USER)

    def invoke(self, arg, from_tty):
        var = gdb.parse_and_eval(arg)
        data = extract_vector(var)
        with open("output.csv", "w") as f:
            writer = csv.DictWriter(f, fieldnames=["id", "name", "value"])
            writer.writeheader()
            writer.writerows(data)
        print("CSV written with {} entries.".format(len(data)))


DumpToJson()
DumpToCsv()
