#!/usr/bin/env python3
#    Upload gains from local file to api.
#    Tim Molteno 2023
#    Phill Brown 2023

import argparse
import csv


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Convert KiCad files for use with Neoden YY1 pick and place machine.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument("--pos", type=str, required=True, help="POS file name.")
    parser.add_argument("--out", type=str, required=True, help="Output file name.")

    ARGS = parser.parse_args()

    # Read the CSV file here
    fname = ARGS.pos
    with open(fname, "r") as f:
        reader = csv.reader(f)
        data = list(reader)

    header = data.pop(0)
    new_data = []   
    for row in data:
        new_data.append(dict(zip(header, row)))


    for row in new_data:
        row['Comment'] = row['Val']
        row['Head'] = '00'
        row['FeederNo'] = '0'
        row['Mount Speed (%)'] = '100'
        row['Pick Height(mm)'] = '0'
        row['Place Height(mm)'] = '0'
        row['Mode'] = '1'
        row['Skip'] = '0'

        footprint = row['Package']
        try:
            parts = footprint.split('_')
            if footprint.endswith('Metric'):
                row['Footprint'] = parts[1] + 'D'
            else:
                row['Footprint'] = parts[1]
        except Exception as e:
            print(e)
            row['Footprint'] = footprint

    output_data = []
    output_header = ['Designator', 'Val', 'Footprint', 'Mid X', 'Mid Y', 
                     'Rotation', 'Head', 'FeederNo', 'Mount Speed (%)', 'Pick Height(mm)', 'Place Height(mm)', 'Mode', 'Skip']
    for row in new_data:
        output_data.append([row[key] for key in output_header])

    ## Write the new CSV file here
    with open(ARGS.out, "w") as f:
        writer = csv.writer(f)
        writer.writerow(output_header)
        writer.writerows(output_data)