//#define HOLDEM_PROFILE

using UdonSharp;
using UnityEngine;

/// <summary>
/// Lightweight frame profiler enabled only when HOLDEM_PROFILE is defined.
/// Every 300 frames dumps a formatted summary of instrumented sections.
/// 
/// Usage:
///   profiler.Begin("SectionName");
///   // ... code ...
///   profiler.End();
/// 
/// Nested Begin/End calls are supported via an internal stack.
/// </summary>
#if HOLDEM_PROFILE
[UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)]
public class HoldemProfiler : UdonSharpBehaviour
{
    const int MAX_SLOTS = 48;
    const int MAX_STACK = 32;
    const int REPORT_INTERVAL = 300;

    // Per-slot accumulated data
    string[] slotNames = new string[MAX_SLOTS];
    float[] slotTotalMs = new float[MAX_SLOTS];
    int[] slotCallCount = new int[MAX_SLOTS];
    int slotCount = 0;

    // Stack for nested Begin/End
    float[] stackStartTimes = new float[MAX_STACK];
    int[] stackSlotIndices = new int[MAX_STACK];
    int stackDepth = 0;

    int frameCount = 0;

    private int FindOrCreateSlot(string name)
    {
        for (int i = 0; i < slotCount; i++)
        {
            if (slotNames[i] == name) return i;
        }
        if (slotCount >= MAX_SLOTS) return -1;
        int idx = slotCount;
        slotNames[idx] = name;
        slotTotalMs[idx] = 0f;
        slotCallCount[idx] = 0;
        slotCount++;
        return idx;
    }

    public void Begin(string name)
    {
        if (stackDepth >= MAX_STACK) return;
        int slot = FindOrCreateSlot(name);
        if (slot < 0) return;
        stackStartTimes[stackDepth] = Time.realtimeSinceStartup;
        stackSlotIndices[stackDepth] = slot;
        stackDepth++;
    }

    public void End()
    {
        if (stackDepth <= 0) return;
        stackDepth--;
        int slot = stackSlotIndices[stackDepth];
        // Safety: skip if Begin didn't register this slot (e.g. MAX_SLOTS full).
        if (slot < 0 || slot >= slotCount) return;
        float elapsed = (Time.realtimeSinceStartup - stackStartTimes[stackDepth]) * 1000f;
        slotTotalMs[slot] += elapsed;
        slotCallCount[slot]++;
    }

    private void Update()
    {
        frameCount++;
        if (frameCount >= REPORT_INTERVAL)
        {
            DumpReport();
            frameCount = 0;
        }
    }

    private void DumpReport()
    {
        string report = $"\n--- HOLDEM PROFILE ({REPORT_INTERVAL} frames) ---\n";
        for (int i = 0; i < slotCount; i++)
        {
            float avg = slotCallCount[i] > 0 ? slotTotalMs[i] / (float)slotCallCount[i] : 0f;
            float total = slotTotalMs[i];
            report += $"{slotNames[i],-40} {total,8:F3}ms total  {avg,8:F3}ms avg  ({slotCallCount[i]} calls)\n";

            // Reset for next interval
            slotTotalMs[i] = 0f;
            slotCallCount[i] = 0;
        }
        Debug.Log(report);
    }
}
#else
// Stub class so the .asset reference doesn't break when HOLDEM_PROFILE is off.
[UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)]
public class HoldemProfiler : UdonSharpBehaviour
{
    public void Begin(string name) { }
    public void End() { }
}
#endif