using LiveOpsExamples;
using UnityEditor;
using UnityEngine;

namespace LiveOpsExamples.Editor
{
  /// <summary>
  /// Bakes the Cozy Collector ScriptableObject assets. Idempotent: writes to
  /// fixed asset paths and overwrites whatever is already there.
  /// </summary>
  public static partial class CozyCollectorBake
  {
    private const string SpriteLibraryAssetPath = "Assets/LiveOpsExamples/CozyCollectorSpriteLibrary.asset";
    private const string SpriteFolderPath = "Assets/LiveOpsExamples/Sprites";

    [MenuItem("Tools/LiveOps/Bake Cozy Collector Assets")]
    public static void BakeAssets()
    {
      var library = AssetDatabase.LoadAssetAtPath<CozyCollectorSpriteLibrary>(SpriteLibraryAssetPath);
      if (library == null)
      {
        library = ScriptableObject.CreateInstance<CozyCollectorSpriteLibrary>();
        AssetDatabase.CreateAsset(library, SpriteLibraryAssetPath);
      }

      var serialized = new SerializedObject(library);
      AssignLibrarySprite(serialized, "background", "cozy-camp-bg.png");
      AssignLibrarySprite(serialized, "player", "player.png");
      AssignLibrarySprite(serialized, "moonberry", "moonberry.png");
      AssignLibrarySprite(serialized, "acorn", "acorn.png");
      AssignLibrarySprite(serialized, "star", "star.png");
      AssignLibrarySprite(serialized, "snack", "snack.png");
      serialized.ApplyModifiedPropertiesWithoutUndo();

      EditorUtility.SetDirty(library);
      AssetDatabase.SaveAssets();
      Debug.Log($"Cozy Collector sprite library baked: {SpriteLibraryAssetPath}");
    }

    private static void AssignLibrarySprite(SerializedObject serialized, string fieldName, string fileName)
    {
      var spritePath = $"{SpriteFolderPath}/{fileName}";
      var sprite = AssetDatabase.LoadAssetAtPath<Sprite>(spritePath);
      if (sprite == null)
      {
        Debug.LogError($"CozyCollectorBake: sprite not found at {spritePath}");
        return;
      }

      var property = serialized.FindProperty(fieldName);
      if (property == null)
      {
        Debug.LogError($"CozyCollectorBake: field '{fieldName}' not found on {nameof(CozyCollectorSpriteLibrary)}");
        return;
      }

      property.objectReferenceValue = sprite;
    }
  }
}
