#!/usr/bin/python3

import sqlite3
import struct
import sys

import sqlite3
import struct
import sys

def get_player_data(db_path, uid):
    """Retrieve player data from the database."""
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute("SELECT Data FROM players WHERE uid = ?", (uid,))
    row = cursor.fetchone()
    conn.close()

    if row:
        return row[0]  # Return BLOB data
    else:
        print(f"No player found with UID {uid}.")
        return None

def find_and_replace_position(data_blob, new_x, new_y, new_z):
    """Modify the position data in the binary BLOB."""
    try:
        # Convert new coordinates to binary format (assuming float32 encoding)
        new_position = struct.pack("<fff", new_x, new_y, new_z)

        # Search for a pattern that looks like a float32 triplet (X, Y, Z)
        for i in range(len(data_blob) - 12):
            possible_x, possible_y, possible_z = struct.unpack("<fff", data_blob[i : i + 12])

            # Ensure coordinates are > 1 and within a reasonable range
            if 1 < possible_x < 100000 and 1 < possible_y < 100000 and 1 < possible_z < 100000:
                print(f"Found position at offset {i}: ({possible_x}, {possible_y}, {possible_z})")

                # Replace with new coordinates
                modified_blob = data_blob[:i] + new_position + data_blob[i + 12:]
                return modified_blob

        print("No valid position data found in BLOB.")
        return None

    except Exception as e:
        print(f"Error processing BLOB data: {e}")
        return None

def update_player_location(db_path, uid, new_x, new_y, new_z):
    """Update player location in the database."""
    data_blob = get_player_data(db_path, uid)
    if not data_blob:
        return

    modified_blob = find_and_replace_position(data_blob, new_x, new_y, new_z)
    if not modified_blob:
        return

    # Update database with modified BLOB
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute("UPDATE players SET Data = ? WHERE uid = ?", (modified_blob, uid))
    conn.commit()
    conn.close()

    print(f"Updated player {uid} to new position: ({new_x}, {new_y}, {new_z})")

if __name__ == "__main__":
    if len(sys.argv) < 6:
        print("Usage: python3 update_dayz_location.py <db_path> <uid> <x> <y> <z>")
        sys.exit(1)

    db_path = sys.argv[1]
    uid = sys.argv[2]
    new_x = float(sys.argv[3])
    new_y = float(sys.argv[4])
    new_z = float(sys.argv[5])

    update_player_location(db_path, uid, new_x, new_y, new_z)

