#include "csv-helpers.hpp"
#include "argparse/argparse.hpp"
#include <iostream>


int main(int argc, char* argv[]) {
    argparse::ArgumentParser program("filter-csv");

    program.add_argument("folder")
        .help("Folder containing CSV files to filter");
    program.add_argument("out_file")
        .help("Output file for filtered CSV file names");
    program.add_argument("--type-filter", "-t")
        .help("Filter CSV files by type")
        .flag();
    program.add_argument("--departure-airport", "-d")
        .help("Filter CSV files by proximity to departure airport (lat, lon)")
        .flag();
    program.add_argument("--arrival-airport", "-a")
        .help("Filter CSV files by proximity to arrival airport (lat, lon)")
        .flag();

    try {
        program.parse_args(argc, argv);
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        std::cerr << program.help().str() << std::endl;
        return 1;
    }

    std::string folder = program.get<std::string>("folder");
    std::string out_file = program.get<std::string>("out_file");
    bool use_type_filter = program.is_used("--type-filter");
    bool use_departure_filter = program.is_used("--departure-airport");
    bool use_arrival_filter = program.is_used("--arrival-airport");

    std::ofstream ofs(out_file);
    if (!ofs.is_open()) {
        std::cerr << "Could not open output file: " << out_file << std::endl;
        return 1;
    }

    std::vector<std::string> csv_files = list_csv_files_in_folder(folder);
    for (const auto& csv_file : csv_files) {
        bool passes_filters = true;
        CSVRow first_row = read_first_csv_row(csv_file);
        if(use_type_filter) {
            passes_filters &= aircraft_type_filter(first_row.t);
        }
        if(use_departure_filter) {
            passes_filters &= near_airport_filter(first_row.lat, first_row.lon, first_row.alt);
        }
        if(use_arrival_filter) {
            CSVRow last_row = read_last_csv_row(csv_file);
            passes_filters &= near_airport_filter(last_row.lat, last_row.lon, last_row.alt);
        }
        if (passes_filters) {
            ofs << csv_file << std::endl;
        }
    }
    ofs.close();
    return 0;
}