#!/usr/bin/env python3
import struct
import numpy as np

imax, jmax = 900, 450
npts = imax * jmax  # 405000
target_bytes = npts * 4  # 1620000 bytes (float32)

campos_grade = []

with open("BAM.fct.06", "rb") as f:
    raw_len = f.read(4)
    endian = ">" if struct.unpack("<I", raw_len)[0] > 10_000_000 else "<"
    f.seek(0)

    while True:
        header = f.read(4)
        if not header:
            break
        rec_bytes = struct.unpack(f"{endian}I", header)[0]

        if rec_bytes == target_bytes:
            arr = np.frombuffer(
                f.read(rec_bytes), dtype=f"{endian}f4"
            ).reshape((jmax, imax))
            campos_grade.append(arr)
            f.seek(4, 1)  # pula marcador final
        else:
            f.seek(rec_bytes + 4, 1)

# Extrai os campos pela ordem do BAM.dir.06
lsm = campos_grade[0]  # 1º campo de grade: LAND SEA ICE MASK
tsurf = campos_grade[2]  # 3º campo de grade: SURFACE TEMPERATURE
veg = campos_grade[13]  # 14º campo de grade: MASK VEGETATION

mar = lsm > 0  # +1.0 = Mar
terra = lsm < 0  # -1.0 = Terra

print("=== 1. SURFACE TEMPERATURE (TSurf) ===")
print(f"Min global : {tsurf.min():.2f} K | Max global : {tsurf.max():.2f} K")
print(
    f"Pontos sobre o MAR com TSurf <= 271.2 K : {np.sum(mar & (np.abs(tsurf) <= 271.2))}"
)
print(
    f"Pontos sobre o MAR com TSurf <= 271.5 K : {np.sum(mar & (np.abs(tsurf) <= 271.5))}"
)
print(
    f"Pontos sobre o MAR com TSurf < 0 (negat): {np.sum(mar & (tsurf < 0))}"
)
print(
    f"Min |TSurf| no MAR: {np.abs(tsurf[mar]).min():.2f} K | Max |TSurf| no MAR: {np.abs(tsurf[mar]).max():.2f} K"
)

print("\n=== 2. MASK VEGETATION (IBIS) ===")
print(f"Valores únicos no MAR  : {np.unique(np.round(veg[mar], 1))}")
print(f"Valores únicos na TERRA: {np.unique(np.round(veg[terra], 1))}")
