#!/usr/bin/env python3
"""Write EdgeWeightGPS spatial weight presets as five raw float32 values."""

from __future__ import annotations

import argparse
import struct
from pathlib import Path


DEFAULT_INSTALL_PATH = Path(
    "/var/home/salt/.var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common/"
    "Cyberpunk 2077/red4ext/plugins/EdgeWeightGPS/spatial_weights.bin"
)

PRESETS: dict[str, tuple[float, float, float, float, float]] = {
    "vanilla": (1.0, 1.0, 1.0, 1.0, 1.0),
    "current": (0.62, 1.0, 1.20, 1.35, 1.05),
    "highway-free": (0.25, 1.10, 1.35, 1.60, 1.15),
    "highway-expensive": (3.0, 1.0, 1.0, 1.0, 1.0),
    "surface-extreme": (0.45, 1.20, 1.80, 2.50, 1.30),
}


def parse_weights(text: str) -> tuple[float, float, float, float, float]:
    values = tuple(float(part) for part in text.split(","))
    if len(values) != 5:
        raise argparse.ArgumentTypeError("expected five comma-separated floats")
    return values  # type: ignore[return-value]


def write_weights(path: Path, values: tuple[float, float, float, float, float]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(struct.pack("<5f", *values))


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("preset", nargs="?", choices=sorted(PRESETS), default="current")
    parser.add_argument("--weights", type=parse_weights, help="five comma-separated floats: H,R,G,P,U")
    parser.add_argument("--output", type=Path, default=DEFAULT_INSTALL_PATH)
    parser.add_argument("--preset-dir", type=Path, help="write every named preset into this directory")
    args = parser.parse_args()

    if args.preset_dir:
        for name, values in PRESETS.items():
            write_weights(args.preset_dir / f"{name}.bin", values)
            print(f"{args.preset_dir / f'{name}.bin'}: {values}")
        return 0

    values = args.weights if args.weights is not None else PRESETS[args.preset]
    write_weights(args.output, values)
    print(f"{args.output}: {values}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
