/* main.c -- pemroses file CSV dari command line. */

#include "csv_reader.h"
#include "parser.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void penggunaan(const char *prog) {
    fprintf(stderr, "Penggunaan: %s <file.csv> [kolom_statistik]\n", prog);
    fprintf(stderr, "  kolom_statistik: indeks kolom (0-indexed) untuk dihitung statistiknya.\n");
}

int main(int argc, char **argv) {
    if (argc < 2) {
        penggunaan(argv[0]);
        return 1;
    }
    const char *path = argv[1];
    int kolom_stat = -1;
    if (argc >= 3) {
        kolom_stat = atoi(argv[2]);
    }

    CsvTable tabel;
    CsvStatus s = csv_baca(path, &tabel);
    if (s != CSV_OK) {
        fprintf(stderr, "Gagal membaca %s (kode %d)\n", path, s);
        return 1;
    }

    printf("Berhasil memuat %d baris (termasuk header).\n\n", tabel.jumlah_baris);
    csv_tampilkan(&tabel, stdout);

    if (kolom_stat >= 0) {
        Statistik stat;
        ParserStatus ps = parser_statistik_kolom(&tabel, kolom_stat, 1, &stat);
        if (ps == PARSER_OK) {
            printf("\n");
            parser_cetak_statistik(&stat, "kolom", stdout);
        } else {
            fprintf(stderr, "Gagal menghitung statistik kolom %d (kode %d)\n",
                    kolom_stat, ps);
            return 1;
        }
    }

    /* Export hasil (sederhana: tulis ulang tabel ke file output). */
    FILE *out = fopen("output.csv", "w");
    if (out != 0) {
        for (int i = 0; i < tabel.jumlah_baris; i++) {
            const CsvRow *r = &tabel.baris[i];
            for (int j = 0; j < r->jumlah_field; j++) {
                fprintf(out, "%s", r->fields[j]);
                if (j < r->jumlah_field - 1) fprintf(out, ",");
            }
            fprintf(out, "\n");
        }
        fclose(out);
        printf("\nHasil ditulis ke output.csv\n");
    }
    return 0;
}
