#!/usr/bin/env bash
# RR3 Asset Packer - Cross-Platform
# Compresses files with ZLIB to create .z format

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}════════════════════════════════════════════════════════════${NC}"
echo -e "${YELLOW}   RR3 Asset Packer - Linux/Unix${NC}"
echo -e "${CYAN}════════════════════════════════════════════════════════════${NC}"
echo ""

# Check Python 3
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}ERROR: Python 3 is not installed!${NC}"
    exit 1
fi

# Check arguments
if [ "$#" -lt 1 ]; then
    echo "Usage: $0 <input_file>"
    echo ""
    echo "Example:"
    echo "  $0 sprites_0.etc.dds"
    echo ""
    echo "Output will be: input_file.z"
    exit 1
fi

INPUT_FILE="$1"

if [ ! -f "$INPUT_FILE" ]; then
    echo -e "${RED}ERROR: Input file not found: $INPUT_FILE${NC}"
    exit 1
fi

OUTPUT_FILE="${INPUT_FILE}.z"

echo -e "${GREEN}Input:${NC}  $INPUT_FILE"
echo -e "${GREEN}Output:${NC} $OUTPUT_FILE"
echo ""

# Pack with Python
python3 - "$INPUT_FILE" "$OUTPUT_FILE" << 'PYTHON_SCRIPT'
import sys
import zlib
import os

input_file = sys.argv[1]
output_file = sys.argv[2]

print("Reading file...")
with open(input_file, "rb") as f:
    data = f.read()

print(f"Input size: {len(data):,} bytes")

print("Compressing with ZLIB (level 9)...")
compressed = zlib.compress(data, level=9)

print(f"Compressed size: {len(compressed):,} bytes")
print(f"Compression ratio: {(1 - len(compressed) / len(data)) * 100:.1f}%")

print("Writing output...")
with open(output_file, "wb") as f:
    f.write(compressed)

print("")
print("✅ Packing complete!")
PYTHON_SCRIPT

echo ""
echo -e "${GREEN}Done!${NC}"
