package main

import (
	"encoding/csv"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
)

func csvToJson(inputSource *os.File) {
	csvReader := csv.NewReader(inputSource)
	headers, err := csvReader.Read()
	if err != nil {
		log.Fatal("Failed to read headers: ", err)
	}
	for {
		record, err := csvReader.Read()
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			log.Fatal("Failed to read the data: ", err)
		}
		if len(record) == len(headers) {
			jsonData := make(map[string]string)
			for i, value := range record {
				jsonData[headers[i]] = value
			}
			jsonOutput, err := json.Marshal(jsonData)
			if err != nil {
				log.Fatal("Failed to convert to json: ", err)
			}
			fmt.Println(string(jsonOutput))
		} else {
			log.Fatal("The number of columns in the record is not equal to the number of headers")
		}
	}

}

func main() {
	inputSource := os.Stdin
	flag.Parse()
	var err error
	if flag.NArg() > 0 {
		inputSource, err = os.Open(flag.Args()[0])
		if err != nil {
			log.Fatalf("Failed to open file: %v\n", err)
		}
		defer inputSource.Close()
	}
	csvToJson(inputSource)

}
