using System;
using System.IO;
using System.Text;
using GTA; // Access to ScriptHookVDotNet functions

public class DataBridge : Script
{
    private readonly string _filePath;
    private int _lastTick = 0;

    public DataBridge()
    {
        // 1. SETUP: Create a folder named 'HudData' in the main GTA directory
        string folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HudData");
        if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

        // Define the path to the JSON file the HTML will read
        _filePath = Path.Combine(folder, "hud_data.json");

        // Subscribe to the Tick event (runs every frame)
        Tick += OnTick;
    }

    private void OnTick(object sender, EventArgs e)
    {
        // 2. PERFORMANCE: Only run this code every 33ms (roughly 30 times per second)
        // Updating every single frame (60-144+ FPS) is unnecessary and heavy on the CPU.
        if (Game.GameTime - _lastTick < 33) return;
        _lastTick = Game.GameTime;

        try
        {
            var p = Game.Player.Character;

            // 3. DATA COLLECTION: Fetch raw stats from the game engine
            int currentHealth = p.Health;
            int maxHealth = p.MaxHealth;
            int armor = p.Armor;
            int money = Game.Player.Money;

            // 4. JSON FORMATTING: Create a string formatted as JSON
            // We use simple string interpolation ($"{}") for speed.
            string json = $"{{\"hp\":{currentHealth},\"max\":{maxHealth},\"arm\":{armor},\"cash\":{money}}}";

            // 5. THE BRIDGE: Write the data to the file
            // FileShare.ReadWrite is the most important part. It allows the HTML file 
            // to "open" and read the file even while C# is writing to it.
            using (var fs = new FileStream(_filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                byte[] info = new UTF8Encoding(true).GetBytes(json);
                fs.Write(info, 0, info.Length);
            }
        }
        catch
        {
            // 6. ERROR HANDLING: If the file is locked for a millisecond, 
            // we ignore the error and just try again on the next tick.
        }
    }
}