// gps_test.cpp — u-blox GPS NMEA test
// Usage: ./gps_test [-v] [-a] [-b BAUD]
//   -v        verbose init debug
//   -a        print ALL NMEA sentences (not just RMC)
//   -b BAUD   set baud rate (default 38400)
//
// Enable UART: sudo raspi-config → Interfaces → Serial Port
//   login shell: No, serial hardware: Yes → reboot
// Check: ls -la /dev/serial0
// Sniff raw bytes to confirm module is transmitting:
//   stty -F /dev/serial0 38400 raw && cat /dev/serial0
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "gps.hpp"

int main(int argc, char **argv)
{
    gps::Config cfg;
    cfg.verbose = false;
    bool show_all = false;

    for (int i = 1; i < argc; ++i) {
        if (std::strcmp(argv[i], "-v") == 0) {
            cfg.verbose = true;
        } else if (std::strcmp(argv[i], "-a") == 0) {
            show_all = true;
        } else if (std::strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
            cfg.baud = std::atoi(argv[++i]);
        }
    }

    std::printf("gps_test: %s @%d baud%s%s\n",
                cfg.dev, cfg.baud,
                cfg.verbose ? " [verbose]" : "",
                show_all    ? " [all sentences]" : "");

    gps::Reader gps;
    if (!gps.begin(cfg)) {
        std::fprintf(stderr, "ERROR: cannot open %s\n"
                             "  Check: UART enabled? (sudo raspi-config)\n"
                             "  Check: ls -la /dev/serial0\n"
                             "  Check: wiring TX=GPIO14 RX=GPIO15\n", cfg.dev);
        return 1;
    }
    std::printf("UART open — waiting for NMEA (Ctrl+C to stop)\n\n");

    char line[128];
    int  fixes = 0;
    for (;;) {
        // 2s per sentence timeout — if nothing arrives, likely wiring or baud mismatch
        if (!gps.readLine(line, sizeof(line), 2000)) {
            std::printf("  [timeout: no NMEA for 2s — check wiring and baud rate]\n");
            continue;
        }

        // Checksum validation
        bool cs_ok = gps::Reader::verifyChecksum(line);
        if (cfg.verbose && !cs_ok)
            std::printf("  [bad checksum] %s", line);

        if (show_all) {
            std::printf("%s", line);
            continue;
        }

        gps::Fix fix;
        if (gps::Reader::parseRmc(line, fix)) {
            if (fix.valid) {
                std::printf("[%4d] %s %s | lat=%+.6f lon=%+.6f spd=%.1fkn%s\n",
                            ++fixes, fix.date, fix.time,
                            fix.lat, fix.lon, fix.speed_knots,
                            cs_ok ? "" : " [bad cs]");
            } else {
                std::printf("       no fix (GPRMC/GNRMC status=V)\n");
            }
        }
    }

    gps.end();
    return 0;
}
