using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class RowingDataRecorder : MonoBehaviour
{
    [Header("Recording Setup")]
    public bool isRecording = false;
    public string saveFileName = "Zone2_Session";
    
    private RowingSessionData _currentSession;
    private float _recordingStartTime;

    private void Start()
    {
        if (PerformanceMonitorManager.Instance != null)
        {
            // We listen to the same events the InputManager uses
            PerformanceMonitorManager.Instance.OnStatsUpdated += RecordStats;
            PerformanceMonitorManager.Instance.OnForceCurveUpdated += RecordForceCurve;
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.R)) ToggleRecording();
    }

    private void ToggleRecording()
    {
        isRecording = !isRecording;
        if (isRecording)
        {
            _currentSession = ScriptableObject.CreateInstance<RowingSessionData>();
            _currentSession.sessionName = saveFileName;
            _recordingStartTime = Time.time;
            Debug.Log($"[Recorder] Started recording: {saveFileName}");
        }
        else
        {
            SaveSessionAsset();
        }
    }

    private void RecordStats(PerformanceMonitorManager.RowingStats stats)
    {
        if (!isRecording) return;
        
        RowingFrame frame = new RowingFrame
        {
            timestamp = Time.time - _recordingStartTime,
            watts = stats.Watts,
            spm = stats.SPM,
            heartRate = stats.HeartRate,
            forceCurve = new List<float>() // Empty for normal stat updates
        };
        _currentSession.frames.Add(frame);
    }

    private void RecordForceCurve(List<float> curve)
    {
        if (!isRecording || curve == null || curve.Count == 0) return;

        // We create a specific frame just for the force curve completion
        RowingFrame frame = new RowingFrame
        {
            timestamp = Time.time - _recordingStartTime,
            watts = PerformanceMonitorManager.Instance.Stats.Watts,
            spm = PerformanceMonitorManager.Instance.Stats.SPM,
            heartRate = PerformanceMonitorManager.Instance.Stats.HeartRate,
            forceCurve = new List<float>(curve) // Clone the list!
        };
        _currentSession.frames.Add(frame);
    }

    private void SaveSessionAsset()
    {
#if UNITY_EDITOR
        if (_currentSession == null || _currentSession.frames.Count == 0) return;
        
        // Create the Asset in your Project folder
        string path = $"Assets/{saveFileName}.asset";
        AssetDatabase.CreateAsset(_currentSession, AssetDatabase.GenerateUniqueAssetPath(path));
        AssetDatabase.SaveAssets();
        
        Debug.Log($"[Recorder] Session saved to {path} with {_currentSession.frames.Count} frames.");
        _currentSession = null;
#endif
    }
}