from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import argparse
import math
import struct
from typing import BinaryIO, Any

import numpy as np


DEVICE_TYPE_NAMES = {
    0: "Cobra",
    4: "Four-hole Cobra",
    5: "Five-hole Cobra",
    13: "Thirteen-hole ECA",
    1000: "DP Module",
    1015: "15-channel DP Module",
    1016: "16-channel DP Module",
    1032: "32-channel DP Module",
    1064: "64-channel DP Module",
    1128: "128-channel DP Module",
    1256: "256-channel DP Module",
    8000: "Force Balance",
    8010: "JR3 Balance",
    8011: "JR3 Balance (A/D)",
    8012: "JR3 Balance (DSP)",
    8020: "Aeroelastic Base Balance",
    10000: "Analog Data Device",
}

DEVICE_TYPE_SHORT_NAMES = {
    0: "Cobra",
    4: "Cobra",
    5: "Cobra",
    13: "ECA",
    1000: "DPM",
    1015: "DPM",
    1016: "DPM",
    1032: "DPM",
    1064: "DPM",
    1128: "DPM",
    1256: "DPM",
    8000: "Force Balance",
    8010: "JR3",
    8011: "JR3",
    8012: "JR3",
    8020: "ABB",
    10000: "ADD",
}

DATA_TYPE_NAMES = {
    0: "Analogue",
    10: "Voltage",
    20: "Pressure",
    30: "Temperature",
    100: "Velocity",
    200: "Force-Moment",
}

DATA_ORDER_NAMES = {
    0: "Non-interleaved",
    1: "Interleaved",
}


@dataclass
class THSettings:
    values: dict[str, Any]

    def __getitem__(self, key: str) -> Any:
        return self.values[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.values[key] = value

    def to_dict(self) -> dict[str, Any]:
        return dict(self.values)


def _read_exact(fid: BinaryIO, size: int) -> bytes:
    data = fid.read(size)
    if len(data) != size:
        raise ValueError("Unexpected end of file")
    return data


def _read_int32(fid: BinaryIO) -> int:
    return struct.unpack("<i", _read_exact(fid, 4))[0]


def _read_int16(fid: BinaryIO) -> int:
    return struct.unpack("<h", _read_exact(fid, 2))[0]


def _read_uint8(fid: BinaryIO) -> int:
    return struct.unpack("<B", _read_exact(fid, 1))[0]


def _read_float64(fid: BinaryIO) -> float:
    return struct.unpack("<d", _read_exact(fid, 8))[0]


def _read_string(fid: BinaryIO) -> str:
    length = _read_int32(fid)
    return _read_exact(fid, length).decode("latin1")


def _read_date(fid: BinaryIO) -> str:
    year = _read_int16(fid)
    month = _read_int16(fid)
    _day_of_week = _read_int16(fid)
    day = _read_int16(fid)
    return datetime(year, month, day).strftime("%d-%b-%Y")


def _read_time(fid: BinaryIO) -> str:
    hour = _read_int16(fid)
    minute = _read_int16(fid)
    second = _read_int16(fid)
    millisecond = _read_int16(fid)
    return f"{hour:02d}:{minute:02d}:{second:02d}.{millisecond:03d}"


def _get_num_samples_per_channel(fid: BinaryIO, num_channels: int) -> int:
    file_pos = fid.tell()
    fid.seek(0, 2)
    file_length = fid.tell()
    fid.seek(file_pos, 0)
    return (file_length - file_pos) // (num_channels * 4)


def _pick_file() -> Path:
    try:
        import tkinter as tk
        from tkinter import filedialog
    except Exception as exc:
        raise ValueError("No file selected and tkinter is not available") from exc

    root = tk.Tk()
    root.withdraw()
    file_name = filedialog.askopenfilename(
        title="Select time-history file to open...",
        filetypes=[("Supported TH files", "*.th? *.th *.bp?")],
    )
    root.destroy()
    if not file_name:
        raise ValueError("No file selected")
    return Path(file_name)


def _device_type_name(device_type: int) -> str:
    return DEVICE_TYPE_NAMES.get(device_type, "Unknown")


def _device_type_short_name(device_type: int) -> str:
    return DEVICE_TYPE_SHORT_NAMES.get(device_type, "Unknown")


def _data_type_name(data_type: int) -> str:
    return DATA_TYPE_NAMES.get(data_type, "Unknown")


def _data_order_name(data_order: int) -> str:
    return DATA_ORDER_NAMES.get(data_order, "Unknown")


def read_th_file(
    file_name: str | Path | None = None,
    num_samples_to_read: int = 0,
    offset: int = 0,
) -> tuple[Any, ...]:
    full_file_name = Path(file_name) if file_name else _pick_file()

    with full_file_name.open("rb") as fid:
        file_format = _read_int32(fid)

        has_pref = 0
        num_channels: int | None = None
        channel_labels: list[str] | None = None
        channel_unit_abrs: list[str] | None = None

        if file_format in {1, 6401}:
            device_id = _read_int32(fid)
            device_name = f"Probe {device_id:03d}"
            device_type = 4
            data_type = 100
            date_string = ""
            time_string = ""
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            has_pref = _read_uint8(fid)
            num_channels = 5 if has_pref else 4
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "deviceName": device_name,
                    "deviceType": _device_type_name(device_type),
                    "deviceID": device_id,
                    "dataType": _data_type_name(data_type),
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "pRef": None,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "fileName": str(full_file_name),
                }
            )
        elif file_format == 2:
            device_id = _read_int32(fid)
            device_name = f"Probe {device_id:03d}"
            device_type = 4
            data_type = 100
            date_string = ""
            time_string = ""
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            p_baro = _read_float64(fid)
            mean_temperature = _read_float64(fid)
            has_pref = _read_uint8(fid)
            num_channels = 5 if has_pref else 4
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "deviceName": device_name,
                    "deviceType": _device_type_name(device_type),
                    "deviceID": device_id,
                    "dataType": _data_type_name(data_type),
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "pBaro": p_baro,
                    "tMean": mean_temperature,
                    "pRef": None,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "fileName": str(full_file_name),
                }
            )
        elif file_format == 3:
            device_type = _read_int32(fid)
            device_id = _read_int32(fid)
            data_type = _read_int32(fid)
            device_name = f"{_device_type_short_name(device_type)} {device_id:03d}"
            date_string = _read_date(fid)
            time_string = _read_time(fid)
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            p_baro = _read_float64(fid)
            mean_temperature = _read_float64(fid)
            has_pref = _read_uint8(fid)
            num_channels = 5 if has_pref else 4
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "deviceName": device_name,
                    "deviceType": _device_type_name(device_type),
                    "deviceID": device_id,
                    "dataType": _data_type_name(data_type),
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "pBaro": p_baro,
                    "tMean": mean_temperature,
                    "pRef": None,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "fileName": str(full_file_name),
                }
            )
        elif file_format == 101:
            data_type = _read_int32(fid)
            data_order = _read_int32(fid)
            num_channels = _read_int32(fid)
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            date_string = _read_date(fid)
            time_string = _read_time(fid)
            channel_labels = [f"Ch {n}" for n in range(1, num_channels + 1)]
            channel_unit_abrs = ["" for _ in range(num_channels)]
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "dataType": _data_type_name(data_type),
                    "dataOrder": _data_order_name(data_order),
                    "numChannels": num_channels,
                    "numSamples": num_samples,
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "chanLabels": channel_labels,
                    "chanUnitAbrs": channel_unit_abrs,
                    "fileName": str(full_file_name),
                }
            )
        elif file_format == 102:
            _header_size = _read_int32(fid)
            data_type = _read_int32(fid)
            data_order = _read_int32(fid)
            num_channels = _read_int32(fid)
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            date_string = _read_date(fid)
            time_string = _read_time(fid)
            channel_labels = [_read_string(fid) for _ in range(num_channels)]
            channel_unit_abrs = [_read_string(fid) for _ in range(num_channels)]
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "dataType": _data_type_name(data_type),
                    "dataOrder": _data_order_name(data_order),
                    "numChannels": num_channels,
                    "numSamples": num_samples,
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "chanLabels": channel_labels,
                    "chanUnitAbrs": channel_unit_abrs,
                    "fileName": str(full_file_name),
                }
            )
        elif file_format == 201:
            device_type = _read_int32(fid)
            device_id = _read_int32(fid)
            device_name = f"{_device_type_short_name(device_type)} {device_id:03d}"
            data_type = _read_int32(fid)
            data_order = _read_int32(fid)
            num_channels = _read_int32(fid)
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            date_string = _read_date(fid)
            time_string = _read_time(fid)
            channel_labels = [f"Ch {n}" for n in range(1, num_channels + 1)]
            channel_unit_abrs = ["" for _ in range(num_channels)]
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "deviceName": device_name,
                    "deviceType": _device_type_name(device_type),
                    "deviceID": device_id,
                    "dataType": _data_type_name(data_type),
                    "dataOrder": _data_order_name(data_order),
                    "numChannels": num_channels,
                    "numSamples": num_samples,
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "chanLabels": channel_labels,
                    "chanUnitAbrs": channel_unit_abrs,
                    "fileName": str(full_file_name),
                }
            )
        elif file_format == 202:
            _header_size = _read_int32(fid)
            device_name = _read_string(fid)
            device_type = _read_int32(fid)
            device_id = _read_int32(fid)
            data_type = _read_int32(fid)
            data_order = _read_int32(fid)
            num_channels = _read_int32(fid)
            num_samples = _read_int32(fid)
            block_size = _read_int32(fid)
            data_rate = _read_float64(fid)
            date_string = _read_date(fid)
            time_string = _read_time(fid)
            channel_labels = [_read_string(fid) for _ in range(num_channels)]
            channel_unit_abrs = [_read_string(fid) for _ in range(num_channels)]
            if num_samples == 0:
                num_samples = _get_num_samples_per_channel(fid, num_channels)
            settings = THSettings(
                {
                    "deviceName": device_name,
                    "deviceType": _device_type_name(device_type),
                    "deviceID": device_id,
                    "dataType": _data_type_name(data_type),
                    "dataOrder": _data_order_name(data_order),
                    "numChannels": num_channels,
                    "numSamples": num_samples,
                    "blockSize": block_size,
                    "dataRate": data_rate,
                    "firstSampleDate": date_string,
                    "firstSampleTime": time_string,
                    "chanLabels": channel_labels,
                    "chanUnitAbrs": channel_unit_abrs,
                    "fileName": str(full_file_name),
                }
            )
        else:
            raise ValueError(f"File format not supported: {file_format}")

        if file_format in {1, 6401, 2, 3}:
            if offset > num_samples:
                raise ValueError("Offset larger than number of samples in file")

            bytes_per_sample = (5 if has_pref else 4) * 4
            block_start_sample = (offset // block_size) * block_size
            fid.seek(block_start_sample * bytes_per_sample, 1)

            if num_samples_to_read == 0:
                num_blocks = num_samples // block_size
            else:
                num_blocks = num_samples_to_read // block_size

            total_samples = num_blocks * block_size
            u = np.zeros(total_samples, dtype=np.float32)
            v = np.zeros(total_samples, dtype=np.float32)
            w = np.zeros(total_samples, dtype=np.float32)
            ps = np.zeros(total_samples, dtype=np.float32)
            if has_pref:
                settings["pRef"] = np.zeros(total_samples, dtype=np.float32)

            for block_num in range(num_blocks):
                index1 = block_num * block_size
                index2 = (block_num + 1) * block_size
                u[index1:index2] = np.frombuffer(_read_exact(fid, block_size * 4), dtype="<f4")
                v[index1:index2] = np.frombuffer(_read_exact(fid, block_size * 4), dtype="<f4")
                w[index1:index2] = np.frombuffer(_read_exact(fid, block_size * 4), dtype="<f4")
                ps[index1:index2] = np.frombuffer(_read_exact(fid, block_size * 4), dtype="<f4")
                if has_pref:
                    settings["pRef"][index1:index2] = np.frombuffer(
                        _read_exact(fid, block_size * 4), dtype="<f4"
                    )

            trimmed_offset = offset - block_start_sample
            if trimmed_offset or (num_samples_to_read and total_samples > num_samples_to_read):
                end = None if num_samples_to_read == 0 else trimmed_offset + num_samples_to_read
                u = u[trimmed_offset:end]
                v = v[trimmed_offset:end]
                w = w[trimmed_offset:end]
                ps = ps[trimmed_offset:end]
                if has_pref and settings["pRef"] is not None:
                    settings["pRef"] = settings["pRef"][trimmed_offset:end]

            return u, v, w, ps, settings.to_dict()

        if offset > num_samples:
            raise ValueError("Offset larger than number of samples in file")

        block_start_sample = (offset // block_size) * block_size
        fid.seek(block_start_sample * num_channels * 4, 1)

        if num_samples_to_read == 0:
            num_blocks = num_samples // block_size
            total_samples = num_blocks * block_size
        else:
            num_blocks = num_samples_to_read // block_size
            total_samples = num_blocks * block_size

        if data_order == 0:
            data = np.zeros((total_samples, num_channels), dtype=np.float32)
            for block_num in range(num_blocks):
                index1 = block_num * block_size
                index2 = (block_num + 1) * block_size
                block = np.frombuffer(
                    _read_exact(fid, block_size * num_channels * 4), dtype="<f4"
                ).reshape((block_size, num_channels), order="F")
                data[index1:index2, :] = block
        elif data_order == 1:
            data = np.frombuffer(_read_exact(fid, total_samples * num_channels * 4), dtype="<f4")
            data = data.reshape((num_channels, total_samples), order="F").T
        else:
            raise ValueError(f"Unsupported data order: {data_order}")

        trimmed_offset = offset - block_start_sample
        if trimmed_offset or (num_samples_to_read and total_samples > num_samples_to_read):
            end = None if num_samples_to_read == 0 else trimmed_offset + num_samples_to_read
            data = data[trimmed_offset:end, :]

        return data, settings.to_dict()


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Read a TH file and print a short summary.")
    parser.add_argument("file", nargs="?", help="Path to the TH file")
    parser.add_argument("--num-samples", type=int, default=0, help="Number of samples to read")
    parser.add_argument("--offset", type=int, default=0, help="Sample offset")
    return parser


def main() -> None:
    args = _build_parser().parse_args()
    result = read_th_file(args.file, num_samples_to_read=args.num_samples, offset=args.offset)

    if len(result) == 5:
        u, v, w, ps, settings = result
        print(f"Read velocity file: {settings['fileName']}")
        print(f"Samples: {len(u)}")
        print(f"Data rate: {settings['dataRate']}")
        print(f"Mean u/v/w/ps: {np.mean(u):.6g} {np.mean(v):.6g} {np.mean(w):.6g} {np.mean(ps):.6g}")
    else:
        data, settings = result
        print(f"Read analogue file: {settings['fileName']}")
        print(f"Shape: {data.shape}")
        print(f"Data rate: {settings['dataRate']}")


if __name__ == "__main__":
    main()
