#!/usr/bin/env python3

import json
import subprocess
import time
import datetime
import sys


def checksum(sentence):
    c = 0
    for ch in sentence:
        c ^= ord(ch)
    return f"{c:02X}"


def dd_to_nmea(value, is_lat):
    value = float(value)
    hemi = ("N" if value >= 0 else "S") if is_lat else ("E" if value >= 0 else "W")
    value = abs(value)

    deg = int(value)
    minutes = (value - deg) * 60

    if is_lat:
        field = f"{deg:02d}{minutes:07.4f}"
    else:
        field = f"{deg:03d}{minutes:07.4f}"

    return field, hemi


def emit(sentence):
    full = f"${sentence}*{checksum(sentence)}"
    print(full, flush=True)


while True:
    try:
        r = subprocess.run(
            ["CoreLocationCLI", "--json"],
            capture_output=True,
            text=True,
            check=True,
            timeout=10
        )

        d = json.loads(r.stdout)

        lat, ns = dd_to_nmea(d["latitude"], True)
        lon, ew = dd_to_nmea(d["longitude"], False)

        now = datetime.datetime.now(datetime.timezone.utc)
        hhmmss = now.strftime("%H%M%S")
        ddmmyy = now.strftime("%d%m%y")

        # RMC: position/time/status
        rmc = f"GPRMC,{hhmmss}.00,A,{lat},{ns},{lon},{ew},0.0,0.0,{ddmmyy},,,A"
        emit(rmc)

        # GGA: position/fix/accuracy-ish
        gga = f"GPGGA,{hhmmss}.00,{lat},{ns},{lon},{ew},1,08,1.0,0.0,M,0.0,M,,"
        emit(gga)

    except Exception as e:
        print(f"# CoreLocation error: {e}", file=sys.stderr, flush=True)

    time.sleep(2)
