#!/usr/bin/env python3
"""
Merge currentPositionLatitude.json + currentPositionLongitude.json into a
single location.json, dropping IP/ID/side.

B and T report identical position values, so only one side (default: B)
is used as the source; lat/long records are joined on exact timestamp
match (confirmed reliable within the same side).

Usage:
    python3 merge_location.py /path/to/boat_dir [--side B]

Reads:
    <boat_dir>/currentPositionLatitude.json
    <boat_dir>/currentPositionLongitude.json

Writes:
    <boat_dir>/location.json
"""

import json
import sys
import argparse
from pathlib import Path


def load_side(path: Path, side: str):
    """Return {timestamp: record} for the given side only."""
    out = {}
    with path.open("r", encoding="utf-8") as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                rec = json.loads(line)
            except json.JSONDecodeError as e:
                print(f"[warn] {path.name}:{line_num} skipped, bad JSON ({e})", file=sys.stderr)
                continue
            if rec.get("side") == side:
                out[rec["timestamp"]] = rec
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("boat_dir", type=Path)
    ap.add_argument("--side", default="B", help="canonical side to source values from (default: B)")
    args = ap.parse_args()

    lat_path = args.boat_dir / "currentPositionLatitude.json"
    lon_path = args.boat_dir / "currentPositionLongitude.json"
    out_path = args.boat_dir / "location.json"

    if not lat_path.exists() or not lon_path.exists():
        print(f"Expected both {lat_path.name} and {lon_path.name} in {args.boat_dir}", file=sys.stderr)
        sys.exit(1)

    lat_by_ts = load_side(lat_path, args.side)
    lon_by_ts = load_side(lon_path, args.side)

    written = 0
    with out_path.open("w", encoding="utf-8") as out_fh:
        for ts, lat_rec in lat_by_ts.items():
            lon_rec = lon_by_ts.get(ts)
            if lon_rec is None:
                print(f"[warn] no matching longitude record for timestamp {ts}", file=sys.stderr)
                continue

            new_record = {
                "component": "location",
                "boat": lat_rec["boat"],
                "end_ts": lat_rec["end_ts"],
                "start_ts": lat_rec["start_ts"],
                "timestamp": ts,
                "value": f"{lat_rec['value']}, {lon_rec['value']}",
            }
            out_fh.write(json.dumps(new_record) + "\n")
            written += 1

    print(f"Wrote {written} records to {out_path}")


if __name__ == "__main__":
    main()
