import numpy as np
from datetime import datetime, timedelta
from pathlib import Path
working_dir = Path(__file__).parent.resolve() if '__file__' in dir() else Path.cwd()

def to_datetime(dtlist):
    return datetime(int(dtlist[0]), int(dtlist[1]), int(dtlist[2]),int(dtlist[3]),int(dtlist[4]),int(float(dtlist[5])),round((float(dtlist[5])%1)*1E6))

def dt2float(dt,dt0):
    return ((dt - dt0) / timedelta(seconds=1)).astype('float')

def gps_week(dt):
    T0 = datetime(1980,1,6)
    return (dt-T0)//timedelta(days=7)

def disp_gnss(gfile,gsat,to_eci):
    from matplotlib import pyplot as plt
    from re import sub
    dt0 = datetime.strptime(sub(r'.*(\d{4}\.\d{3}).*', r'\1', gfile), '%Y.%j')
    with np.load(gfile, allow_pickle=True) as fid:
        Gdata = fid['Gdata']
        Gdt = fid['Gdt']
        Gsats = fid['Gsats']
    if ~np.isin(gsat,Gsats):
        return
    idx = np.where(Gsats == gsat)[0][0]
    Gdata = Gdata[:,idx,:]
    if to_eci:
        from frame_conversions import ro_ecef2eci
        pos, vel = ro_ecef2eci(Gdata[:, :3], Gdata[:, 4:7], Gdt)
        pos /= 1E3
        vel /= 1E3
    else:
        pos = Gdata[:, :3]
        vel = Gdata[:, 4:7] / 1E4
    fig, axs = plt.subplots(3, 1, figsize=(12, 9))
    axs[0].plot(dt2float(Gdt, dt0) / 3600, pos, '.', ms=0.5)
    axs[1].plot(dt2float(Gdt, dt0) / 3600, vel, '.', ms=0.5)
    axs[2].plot(dt2float(Gdt, dt0) / 3600, Gdata[:, 3], '.', ms=0.5)
    for ax in axs:
        ax.grid(True)
        ax.set_xlim((0, 72))
        ax.set_xticks(range(0, 75, 12))
    axs[0].set_title(gsat)
    # axs[2].set_ylim((-1000, 1000))
    axs[0].set_ylabel('Position (km)')
    axs[1].set_ylabel('Velocity (km/s)')
    axs[2].set_ylabel('Clock Bias (us)')
    axs[2].set_xlabel(f'Hours of {dt0:%Y-%m-%d}')
    fig.savefig(sub(r'.*/(.*)\.npz',r'\1.png',gfile), dpi=300)

def read_GNSS(file):
    Gsats = []
    Gdata = []
    isdata = False
    for line in open(file,'r'):
        if not isdata and line.startswith('+ '):
            Gsats = Gsats + [line[x:x + 3] for x in range(9, 60, 3) if line[x] != ' ']
        elif not isdata and line.startswith('*'):
            isdata = True
            Gsats = np.array(Gsats)
            Gtmp = np.full((len(Gsats),8), np.nan)
            Gdt = [to_datetime(line[1:].split())]
        elif isdata and line.startswith('*'):
            Gdata.append(Gtmp.copy())
            Gdt.append(to_datetime(line[1:].split()))
        elif isdata and line.startswith('P'):
            Gtmp[Gsats==line[1:4],:4] = np.array([line[x:x+14] for x in range(4,60,14)]).astype('float')
        elif isdata and line.startswith('V'):
            Gtmp[Gsats==line[1:4],4:] = np.array([line[x:x+14] for x in range(4,60,14)]).astype('float')
        elif isdata and line.startswith('EOF'):
            Gdata.append(Gtmp.copy())
            break
    Gdt = np.array(Gdt)
    Gdata = np.array(Gdata)
    Gdata[np.abs(Gdata - 1E6) < 1E-3] = np.nan
    return Gdata, Gdt, Gsats

def lagrange(X, Y, x, order):
    X = np.ravel(X)
    nX = len(X)
    nx = len(x)
    if Y.ndim == 1:
        y = np.full((nx, ), np.nan)
        dy = np.full((nx,), np.nan)
    else:
        y = np.full((nx, Y.shape[1]), np.nan)
        dy = np.full((nx, Y.shape[1]), np.nan)

    T = X[:, None] - X[None, :]
    np.fill_diagonal(T, 1)
    for ii in range(nx):
        idx = np.searchsorted(X, x[ii])
        idxL = max(min(idx - order, nx - 2 * order), 0)
        if idx < X.size and X[idx] == x[ii]:
            idxR = min(max(idx + order + 1, 2 * order), nX)
            J = np.arange(idxL, idxR)
            pX0 = x[ii] - X[J]
            R = np.prod(T[J][:, J], axis=1)
            y[ii] = Y[idx]
            pX1 = pX0[pX0 != 0]
            vX = np.full_like(pX0, np.prod(pX1))
            vX[pX0 == 0] *= np.sum(1 / pX1)
            vX[pX0 != 0] /= pX1
            dy[ii] = (vX / R) @ Y[J]
        else:
            idxR = min(max(idx + order, 2 * order), nX)
            J = np.arange(idxL, idxR)
            pX0 = x[ii] - X[J]
            R = np.prod(T[J][:, J], axis=1)
            pX = np.prod(pX0) / pX0 # method 1, quick as it multiplies all numerators and all denominators before division
            vX = pX * (np.sum(1 / pX0) - 1 / pX0)
            y[ii] = (pX / R) @ Y[J]
            dy[ii] = (vX / R) @ Y[J]
            # pX = np.tile(x[ii] - X[J], (len(J), 1)) # method 2, reduce error as it pairs numerators and denominators
            # np.fill_diagonal(pX, 1)
            # R = T[J][:,J]
            # y[ii] = np.prod(pX / R, axis=1) @ Y[J]
    return y, dy

# TC: updated 2026-10-28 (new functions from this line)
def read_navbit(fname, gtype):
    from pathlib import Path
    from struct import unpack
    fname = Path(fname)
    raw = fname.read_bytes()
    if gtype == 'G':
        if fname.name.startswith('cdbsV2_'):
            tag, prn, mask, pmask, gsec = unpack('<6sHHHI', raw[:16])
        elif fname.name.startswith('cdbs_'):
            tag, prn, cn0, mask, pmask, gsec = unpack('<6sBBBBI', raw[:16])
        else:
            return None, None
        chunks = np.unpackbits(np.frombuffer(raw[16:], dtype=np.uint8), bitorder='little').reshape(50, 32)
        return chunks[:, -3::-1].ravel(), np.repeat(np.unpackbits(np.array([pmask],dtype=np.uint8))[3:],300)
    elif gtype == 'R':
        TIME_MARK = '111110001101110101000010010110'
        PIDX = ['0101010101010101010110101010101010101010101010101011010101010101011010101101100000001',
                '0110011001100110011011001100110011001100110011001101100110011001101100110110100000010',
                '1000011110000111100011110000111100001111000011110001111000011110001111000111000000100',
                '0000011111111000000011111111000000001111111100000001111111100000001111111000000001000',
                '1111100000000000000011111111111111110000000000000001111111111111110000000000000010000',
                '0000000000000000000011111111111111111111111111111110000000000000000000000000000100000',
                '1111111111111111111100000000000000000000000000000000000000000000000000000000001000000',
                '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111']
        PIDX = np.array([np.array(list(pp)) == '1' for pp in PIDX])
        tag, svn, snr, mask, pmask, gsec = unpack('<6sBBHHI', raw[:16])
        chunks = np.unpackbits(np.frombuffer(raw[16:], dtype=np.uint8)).reshape(15, 200)
        frame_checks = np.all([np.all(chunks[:, :170:2] != chunks[:, 1:170:2], axis=1),
                               [255-[int(np.sum(ch[ss]) % 2) for ss in PIDX]@np.array([128,64,32,16,8,4,2,1]) in [2,4,8,16,32,64,128,255] for ch in chunks[:, :170:2]],
                               [''.join(map(str,ch)) == TIME_MARK for ch in chunks[:,170:]],
                               chunks[:,2:10:2]@[8,4,2,1]==np.arange(15)+1], axis=0)
        nav_bits = np.zeros((15, 100), dtype=np.uint8)
        nav_bits[:, :85] = np.cumsum(chunks[:, :170:2], axis=1)%2
        return nav_bits.ravel(), np.repeat(frame_checks,100).astype(np.uint8)
    else:
        return None, None

def proc_gnss_bit(tgzfile):
    from pathlib import Path
    import tarfile
    from shutil import rmtree
    from datetime import datetime, timedelta
    from re import sub
    # from rd_cdbs import rd_cdbs
    # from rd_cdbs_glonass import rd_cdbs_glonass
    gps_t0 = datetime(1980, 1, 6)
    # print(f'{working_dir.as_posix()}', flush=True)
    tgzfile = Path(tgzfile)
    if tgzfile.is_file():
        tgz_t0 = datetime.strptime(sub(r'.*_(\d{4}\.\d{3}\.\d\d\.\d\d)\..*',r'\1',tgzfile.name),'%Y.%j.%H.%M')
        tgz_sec0 = int((tgz_t0 - gps_t0).total_seconds())
        data_dir = working_dir / 'gnssBin'
        rmtree(data_dir, ignore_errors=True)
        data_dir.mkdir(parents=True, exist_ok=True)
        with tarfile.open(tgzfile, "r:gz") as tar:
            tar.extractall(path=data_dir)
    elif tgzfile.is_dir():
        tgz_t0 = datetime.strptime(tgzfile.parent.name+tgzfile.name, '%Y%m%d%H')
        tgz_sec0 = int((tgz_t0 - gps_t0).total_seconds())
        data_dir = tgzfile
    else:
        return
    out_dir = working_dir / f'gnssNavBit/{tgz_t0:%Y.%j}'
    out_dir.mkdir(parents=True, exist_ok=True)

    gsats = []
    gdata = np.zeros((0, 3630 * 50, 3), dtype='uint8')
    rsats = []
    rdata = np.zeros((0, 3630 * 50, 3), dtype='uint8')
    for binfile in data_dir.rglob('*.bin'):
        if binfile.name.startswith('cdbs_'):
            gnss = 'G' + binfile.name[5:7]
        elif '_CA_' in binfile.name:
            gnss = binfile.name[7:10]
        else:
            # binfile.unlink()
            continue
        if gnss[0] == 'G':
            if gnss not in gsats:
                gsats.append(gnss)
                gdata = np.vstack((gdata, np.zeros((1, 3630 * 50, 3), dtype='uint8')))
            gidx = gsats.index(gnss)
            t0 = int(sub(r'.*_(\d{10})_.*', r'\1', binfile.name))
            tidx0 = (t0 - tgz_sec0) * 50
            fgb, fgbq = read_navbit(binfile, 'G')
            gdata[gidx, tidx0:tidx0 + len(fgb), 0] += fgb * fgbq
            gdata[gidx, tidx0:tidx0 + len(fgb), 1] += (1 - fgb) * fgbq
            gdata[gidx, tidx0:tidx0 + len(fgb), 2] += 1 - fgbq
        elif gnss[0] == 'R':
            if gnss not in rsats:
                rsats.append(gnss)
                rdata = np.vstack((rdata, np.zeros((1, 3630 * 50, 3), dtype='uint8')))
            gidx = rsats.index(gnss)
            t0 = int(sub(r'.*_(\d{10})_.*', r'\1', binfile.name))
            tidx0 = (t0 - tgz_sec0) * 50
            fgb, fgbq = read_navbit(binfile, 'R')
            rdata[gidx, tidx0:tidx0 + len(fgb), 0] += fgb * fgbq
            rdata[gidx, tidx0:tidx0 + len(fgb), 1] += (1 - fgb) * fgbq
            rdata[gidx, tidx0:tidx0 + len(fgb), 2] += 1 - fgbq
    for gg, gnss in enumerate(gsats):
        outfile = out_dir / f'navBit_{gnss}_{tgz_t0:%Y.%j.%H}.npz'
        if outfile.is_file():
            with np.load(outfile) as fid:
                navbit = np.unpackbits(fid['navbit'])
                navbitmask = np.unpackbits(fid['navbitmask'])
        else:
            navbit = np.full((3600 * 50, ), False)
            navbitmask = np.full((3600 * 50, ), False)
        idx = np.where(gdata[gg, :, 0] + gdata[gg, :, 1] > 2 * gdata[gg, :, 2])[0]
        if np.any(idx >= (60 - tgz_t0.minute) * 3000):
            idx0 = idx[idx < (60 - tgz_t0.minute) * 3000]
            navbitmask[idx0 + tgz_t0.minute * 3000] = True
            navbit[idx0 + tgz_t0.minute * 3000] = gdata[gg, idx0, 0] > gdata[gg, idx0, 1]
            np.savez(outfile, navbit=np.packbits(navbit), navbitmask=np.packbits(navbitmask))
            out_dir1 = working_dir / f'gnssNavBit/{tgz_t0 + timedelta(hours=1):%Y.%j}'
            out_dir1.mkdir(exist_ok=True, parents=True)
            outfile = out_dir1 / f'navBit_{gnss}_{tgz_t0 + timedelta(hours=1):%Y.%j.%H}.npz'
            if outfile.is_file():
                with np.load(outfile) as fid:
                    navbit = np.unpackbits(fid['navbit'])
                    navbitmask = np.unpackbits(fid['navbitmask'])
            else:
                navbit = np.full((3600 * 50,), False)
                navbitmask = np.full((3600 * 50,), False)
            idx0 = idx[idx >= (60 - tgz_t0.minute) * 3000]
            navbitmask[idx0 - (60 - tgz_t0.minute) * 3000] = True
            navbit[idx0 - (60 - tgz_t0.minute) * 3000] = gdata[gg, idx0, 0] > gdata[gg, idx0, 1]
            np.savez(outfile, navbit=np.packbits(navbit), navbitmask=np.packbits(navbitmask))
        else:
            navbitmask[idx + tgz_t0.minute * 3000] = True
            navbit[idx + tgz_t0.minute * 3000] = gdata[gg, idx, 0] > gdata[gg, idx, 1]
            np.savez(outfile, navbit=np.packbits(navbit), navbitmask=np.packbits(navbitmask))
    for gg, gnss in enumerate(rsats):
        outfile = out_dir / f'navBit_{gnss}_{tgz_t0:%Y.%j.%H}.npz'
        if outfile.is_file():
            with np.load(outfile) as fid:
                navbit = np.unpackbits(fid['navbit'])
                navbitmask = np.unpackbits(fid['navbitmask'])
        else:
            navbit = np.full((3600 * 50, ), False)
            navbitmask = np.full((3600 * 50, ), False)
        idx = np.where(rdata[gg, :, 0] + rdata[gg, :, 1] > 2 * rdata[gg, :, 2])[0]
        if np.any(idx >= (60 - tgz_t0.minute) * 3000):
            idx0 = idx[idx < (60 - tgz_t0.minute) * 3000]
            navbitmask[idx0 + tgz_t0.minute * 3000] = True
            navbit[idx0 + tgz_t0.minute * 3000] = rdata[gg, idx0, 0] > rdata[gg, idx0, 1]
            np.savez(outfile, navbit=np.packbits(navbit), navbitmask=np.packbits(navbitmask))
            out_dir1 = working_dir / f'gnssNavBit/{tgz_t0 + timedelta(hours=1):%Y.%j}'
            out_dir1.mkdir(exist_ok=True, parents=True)
            outfile = out_dir1 / f'navBit_{gnss}_{tgz_t0 + timedelta(hours=1):%Y.%j.%H}.npz'
            if outfile.is_file():
                with np.load(outfile) as fid:
                    navbit = np.unpackbits(fid['navbit'])
                    navbitmask = np.unpackbits(fid['navbitmask'])
            else:
                navbit = np.full((3600 * 50,), False)
                navbitmask = np.full((3600 * 50,), False)
            idx0 = idx[idx >= (60 - tgz_t0.minute) * 3000]
            navbitmask[idx0 - (60 - tgz_t0.minute) * 3000] = True
            navbit[idx0 - (60 - tgz_t0.minute) * 3000] = rdata[gg, idx0, 0] > rdata[gg, idx0, 1]
            np.savez(outfile, navbit=np.packbits(navbit), navbitmask=np.packbits(navbitmask))
        else:
            navbitmask[idx + tgz_t0.minute * 60 * 50] = True
            navbit[idx + tgz_t0.minute * 60 * 50] = rdata[gg, idx, 0] > rdata[gg, idx, 1]
            np.savez(outfile, navbit=np.packbits(navbit), navbitmask=np.packbits(navbitmask))
    return

