#!/usr/bin/env bash
set -euo pipefail

if [[ $# -lt 3 ]]; then
  echo "usage: $0 <game-dir> <archive-or-archive-dir> <work-dir> [resource-regex] [resource-path] [mod-name]" >&2
  exit 2
fi

game_dir=$1
archive_path=$2
work_dir=$3
resource_regex=${4:-'all\.traffic_persistent$'}
resource_path=${5:-'base/worlds/03_night_city/sectors/_generated/traffic/all.traffic_persistent'}
mod_name=${6:-zz_edge_weight_gps}

raw_dir="${work_dir}/01_raw"
json_dir="${work_dir}/02_json"
patched_json_dir="${work_dir}/03_json_patched"
patched_raw_dir="${work_dir}/04_raw_patched"
pack_root="${work_dir}/${mod_name}"
packed_dir="${work_dir}/05_packed"
resource_dir=$(dirname "${resource_path}")
resource_file=$(basename "${resource_path}")
resource_hash=3419764573789342681

mkdir -p "${raw_dir}/${resource_dir}" "${json_dir}" "${patched_json_dir}" "${patched_raw_dir}" "${pack_root}/${resource_dir}" "${packed_dir}"

if [[ -f "${archive_path}" ]]; then
  kark_path="${raw_dir}/${resource_file}.kark"
  decompressed_base="${raw_dir}/${resource_file}.raw"
  python3 tools/extract_archive_segment.py "${archive_path}" "${resource_hash}" "${kark_path}"
  tools/cp77_toolbox.sh oodle decompress "${kark_path}" "${decompressed_base}" || true
  if [[ ! -f "${decompressed_base}.bin" ]]; then
    echo "failed to decompress ${kark_path}" >&2
    exit 1
  fi
  mv "${decompressed_base}.bin" "${raw_dir}/${resource_path}"
else
  echo "raw segment extraction needs a single archive file, got: ${archive_path}" >&2
  exit 2
fi

tools/cp77_toolbox.sh convert serialize "${raw_dir}" --outpath "${json_dir}"

python3 tools/patch_traffic_lanes.py "${json_dir}" "${patched_json_dir}" --copy-unchanged

tools/cp77_toolbox.sh convert deserialize "${patched_json_dir}" --outpath "${patched_raw_dir}"

cp "${patched_raw_dir}/${resource_file}" "${pack_root}/${resource_path}"

tools/cp77_toolbox.sh pack "${pack_root}" --outpath "${packed_dir}"

echo "packed archive output: ${packed_dir}"
