import json


# Transform value in metadata
def transform_value(key, value):
    if isinstance(value, dict):
        if "Value" in value and "Unit" in value:
            value_type = "str" if isinstance(value["Value"], str) else "float"
            return {
                "key": key,
                "type": "dict",
                "value": [
                    {"key": "Value", "type": value_type, "value": value["Value"]},
                    {"key": "Unit", "type": "str", "value": value["Unit"]},
                ],
            }
        else:
            return {
                "key": key,
                "type": "dict",
                "value": [transform_value(k, v) for k, v in value.items()],
            }
    elif isinstance(value, list):
        return {
            "key": key,
            "type": "list",
            "value": [transform_value("", item) for item in value],
        }
    elif isinstance(value, str):
        return {"key": key, "type": "str", "value": value}
    else:
        raise ValueError(f"Unsupported value type: {type(value)}")


def my_json_to_kadi(data):
    return [transform_value(key, value) for key, value in data.items()]


# Print the output JSON in a formatted way
# Some example JSON inputs for testing
input_json = {
    "Material": {
        "Name": "LLTO",
        "Composition": "(Li,La)TiO-type",
        "Type": "Perovskite-type",
        "Properties": {
            "Ionic Conductivity": {"Value": "10^-3", "Unit": "S cm^-1"},
            "Chemical Stability": "",
            "Dendrite Formation Risk": "",
            "Operating Voltage": "",
            "Flexibility": "",
            "Processing": "",
        },
    },
    "Performance": {
        "Specific Capacity": {"Value": "", "Unit": ""},
        "Energy Density": {"Value": "", "Unit": ""},
        "Capacity Retention": "",
        "Operating Temperature": {"Value": "Room temperature", "Unit": ""},
    },
    "Usage": {"Battery Type": "", "Benefits": []},
}

# Another test
input_json = {
    "Experiment": {
        "Material": "LATP powders",
        "SynthesisRoute": "modified sol-gel synthesis route described by (Bucharsky et al., 2015)",
        "Precursors": [
            {
                "Name": "lithium acetate Li(C2H3O2) ⋅2H2O",
                "Purity": "purity ≥ 99 %",
                "Supplier": "Alfa Aesar GmbH & Co KG",
                "Location": "Germany",
            },
            {
                "Name": "aluminum nitrate Al(NO3)3 ⋅9H2O",
                "Purity": "purity ≥ 98.5 %",
                "Supplier": "Merck KGaA",
                "Location": "Germany",
            },
            {
                "Name": "titanium-isopropoxide Ti[OCH(CH3)2]4",
                "Purity": "purity ≥ 98 %",
                "Supplier": "Merck KGaA",
                "Location": "Germany",
            },
        ],
        "Procedure": [
            {
                "Step": "Dissolve lithium acetate and aluminum nitrate in distilled water under constant stirring."
            },
            {"Step": "Add titanium-isopropoxide dropwise to the solution."},
            {"Step": "Add phosphoric acid slowly through a drip funnel to form a gel."},
            {"Step": "Dry the gel at room temperature for 24 h."},
        ],
        "HeatTreatment": [
            {
                "Step": "First, heat treat samples at 400°C for 6 h to achieve precursor formation and eliminate reaction gases."
            },
            {
                "Step": "Second, process samples at 900°C for 8 h to complete the reaction to crystalline LATP."
            },
        ],
        "BatchVariations": [
            {
                "Description": "Prepare one batch with all precursors in stoichiometric quantities (marked as 0.0 wt%)."
            },
            {
                "Description": "Explore different batches with either an excess up to +7.5 wt% or a deficiency up to -15.0 wt% of phosphoric acid compared to the stoichiometric composition."
            },
        ],
        "Processing": [
            {"Step": "Process the obtained powders in a planetary ball mill."},
            {
                "Step": "Form pellets by uniaxial pressing and then further densify by cold isostatic pressing at 400 MPa."
            },
            {
                "Step": "All pressed samples have a green density of approximately 62% relative density."
            },
        ],
        "Sintering": {
            "TemperatureRange": "850 to 1,050°C",
            "IsothermalSinteringTime": "30 to 540 min",
            "Cooling": "Cool down to room temperature in furnace",
            "DensityDetermination": "Determine densities by Archimedes’ method",
        },
        "IonicConductivityMeasurements": {
            "Method": "Impedance analysis",
            "Conditions": "At room temperature over the frequency range from 0.1 Hz to 1 MHz with an AC amplitude of 50 mV in the frequency response analyzer (AMTEK GmbH, VersaSTAT 4, Pennsylvania, United States)",
            "Reference": "For further details of the experimental part please refer to our previous work (Schiffmann et al., 2021)",
        },
    }
}


if __name__ == "__main__":
    # Transform the input JSON
    from kadi_apy.lib.conversion import json_to_kadi

    output_json = json_to_kadi(input_json)

    # Print the output JSON
    print(json.dumps(output_json, indent=2))