#!/usr/bin/env python3
"""Test data for satellites outside BNC's range (case eph_out_of_range): the
first 6 minutes of data/eph_vote_261118_20min.raw, where each GPS ephemeris
(1019) of G24 from ASCG00SHN0, KERG00ATF0 and OWMG00NZL0 is followed by a copy
with satellite ID 39 (as broadcast by the NTS-3 test signal since 30 Sep 2026).

    mk_eph_g39.py data/eph_vote_261118_20min.raw data/eph_g39_261118_6min.raw
"""
import sys
import bncraw

STATIONS = {"ASCG00SHN0", "KERG00ATF0", "OWMG00NZL0"}


def with_sv(payload, sv):
    p = bytearray(payload)          # satellite ID: bits 12-17 after the message number
    p[1] = (p[1] & 0xF0) | (sv >> 2)
    p[2] = (p[2] & 0x3F) | ((sv & 0x03) << 6)
    return bytes(p)


def main():
    src, out = sys.argv[1], sys.argv[2]
    chunks = []
    framers = {}
    for t, sta, fmt, data in bncraw.read_chunks(src):
        if t >= "2026-11-18T17:49":
            break
        chunks.append((t, sta, fmt, data))
        if sta not in STATIONS:
            continue
        extra = b""
        for p in framers.setdefault(sta, bncraw.Rtcm3Framer()).feed(data):
            if bncraw.msg_type(p) == "1019" and bncraw.BitReader(p).u(18) & 0x3F == 24:
                extra += bncraw.frame(with_sv(p, 39))
        if extra:
            chunks.append((t, sta, fmt, extra))
    bncraw.write_chunks(out, chunks)


if __name__ == "__main__":
    main()
