using UnityEngine;
using System.Collections.Generic;
using ChillConnect;
using IgnoreOPS;

public class LevelManager : MonoBehaviour
{
    // 单例实例
    public static LevelManager Instance { get; private set; }

    // 当前加载的关卡配置
    public LevelConfig CurrentLevel { get; private set; }

    // 关卡文件在 Resources 下的路径前缀
    private const string LevelResourcePath = "Levels/lv";

    private void Awake()
    {
        // 单例初始化：保证全局只有一个实例
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        // 可选：跨场景不销毁
        // DontDestroyOnLoad(gameObject);
    }

    private void OnDestroy()
    {
        // 销毁时清空单例引用，防止内存泄漏
        if (Instance == this)
        {
            Instance = null;
        }
    }

    /// <summary>
    /// 按关卡ID加载单个关卡配置
    /// </summary>
    /// <param name="levelId">关卡ID</param>
    /// <returns>加载成功返回true</returns>
    public bool LoadLevel(int levelId)
    {
        levelId -= 1; 
        if (levelId < 0)
        {
            Debug.LogError("关卡ID必须大于0");
            return false;
        }
        var gameConfigs = ConfigSystem.GetConfig<ArrowGameConfigModel>().DataList;
        if (levelId >= gameConfigs.Count)
        {
            levelId = gameConfigs.Count - 1;
        }
        
        var jsonFile = gameConfigs[levelId];
        
        if (jsonFile == null)
        {
            Debug.LogError($"关卡文件加载失败：{LevelResourcePath}{levelId}");
            return false;
        }

        var curlevelConfig = new LevelConfig()
        {
            levelId = jsonFile.id,
            levelName = jsonFile.levelName,
            gridRows = jsonFile.gridRows,
            gridCols = jsonFile.gridCols,
            pointSpacing = jsonFile.pointSpacing,
            arrows = SerializeUtil.ToObject<List<ArrowConfig>>(jsonFile.arrows)
        };

        CurrentLevel = curlevelConfig;
        
        if (CurrentLevel == null || CurrentLevel.arrows == null)
        {
            Debug.LogError($"关卡 {levelId} 配置解析失败");
            return false;
        }

        Debug.Log($"关卡 {levelId} 加载成功：{CurrentLevel.levelName}，箭头数：{CurrentLevel.arrows.Count}");
        return true;
    }

    /// <summary>
    /// 按完整文件名加载关卡（不含.json后缀）
    /// </summary>
    public bool LoadLevelByName(string fileName)
    {
        TextAsset jsonFile = Resources.Load<TextAsset>(fileName);
        if (jsonFile == null)
        {
            Debug.LogError($"关卡文件加载失败：{fileName}");
            return false;
        }

        CurrentLevel = JsonUtility.FromJson<LevelConfig>(jsonFile.text);
        return CurrentLevel != null;
    }
}
