#include "CsvParser.h"
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <iostream>
#include <algorithm> // For std::remove_if

namespace CsvParser {

TickData parseTickCsvLine(std::string_view line) {
    TickData tick;
    std::string s_line(line); // Convert string_view to string for stringstream
    std::stringstream ss(s_line);
    std::string segment;
    std::vector<std::string> seglist;

    while(std::getline(ss, segment, ',')) {
        seglist.push_back(segment);
    }

    if (seglist.size() != 3) {
        throw std::runtime_error("CSV line does not have 3 segments: " + std::string(line));
    }

    // Parse timestamp (simplified for now, assumes epoch seconds)
    // In a real scenario, this would involve more robust date/time parsing
    try {
        long long timestamp_sec = std::stoll(seglist[0]);
        tick.timestamp = std::chrono::system_clock::from_time_t(timestamp_sec);
    } catch (const std::exception& e) {
        throw std::runtime_error("Failed to parse timestamp: " + seglist[0] + " - " + e.what());
    }

    // Parse price
    try {
        tick.price = std::stod(seglist[1]);
    } catch (const std::exception& e) {
        throw std::runtime_error("Failed to parse price: " + seglist[1] + " - " + e.what());
    }

    // Parse volume
    try {
        tick.volume = std::stol(seglist[2]);
    } catch (const std::exception& e) {
        throw std::runtime_error("Failed to parse volume: " + seglist[2] + " - " + e.what());
    }

    return tick;
}

std::vector<TickData> parseTickCsvFile(std::string_view filename) 
{
    std::vector<TickData> ticks;
    std::ifstream file(std::string{filename}); // Convert string_view to string for ifstream

    if (!file.is_open()) {
        throw std::runtime_error("Could not open file: " + std::string(filename));
    }

    std::string line;
    while (std::getline(file, line)) {
        if (line.empty()) continue; // Skip empty lines
        try {
            ticks.push_back(parseTickCsvLine(line));
        } catch (const std::runtime_error& e) {
            std::cerr << "Error parsing line: \"" << line << "\" - " << e.what() << std::endl;
            // Depending on requirements, could rethrow or continue
        }
    }
    return ticks;
}

} // namespace CsvParser
