import json


def convertrowtojson(row):
    """
    Convert line of data from spreadsheet into Open Carbon format
    """

    start = str(row['Latest year - Start'])
    end = str(row['Latest year - End'])

    # Make simplified assumptions about exact start and end date based on start/end year
    # If start = end, we assume calendar year
    # Otherwise assume standard accounting year

    if start == end:
        start += '-01-01T00:00:00'
        end += '-12-31T00:00:00'
    else:
        start += '-04-01T00:00:00'
        end += '-03-31T00:00:00'

    fields = {
        "Scope 1" : {'unit': 'TCO2E', 'measure': 'scope1'},	
        "Scope 2 - Location-based" : {'unit': 'TCO2E', 'measure': 'scope2.location'},	
        "Scope 2 - Market-based" : {'unit': 'TCO2E', 'measure': 'scope2.market'},	
        "Scope 1 & 2 - Location-based" : {'unit': 'TCO2E', 'measure': 'scope1and2.location'},	
        "Scope 1 & 2 - Market-based" : {'unit': 'TCO2E', 'measure': 'scope1and2.market'},
        "Scope 3" : {'unit': 'TCO2E', 'measure': 'scope3'},	
        "Floor area (m2)" : {'unit': 'M2', 'measure': 'floor.area'}
    }

    datajson = [{
        "sourceurl": row['Report URL'],
        "sourcepage": str(row['Page']),
        "sourcecomments": row['Comments'],
        "periodstart": start,
        "periodend": end,
        "dataitems": []
    }]

    for field in fields:
        if row[field] != "":
            datajson[0]["dataitems"].append({
                "measure": fields[field]['measure'],
                "unit": fields[field]['unit'],
                "value": str(row[field])
            })

    return json.dumps(datajson, indent=2)