using System.IO;
using UnityEngine;

public class App : MonoBehaviour
{
    public static ScriptVM VM { get; private set; }
    public static ScriptLoader Loader { get; private set; }
    public static GameState GameState { get; private set; }
    public static CameraController CameraController { get; private set; }
    public static UIManager UI { get; private set; }
    public static TextManager TextManager { get; private set; }
    public static VideoPlayer VideoPlayer { get; private set; }
    public static SceneLoader SceneLoader { get; private set; }
    public static ResourceManager ResourceManager { get; private set; }

    public const float Ps1FPS = 60f;


    [SerializeField] private string startScript;

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        InitializeManagers();

        // УБИРАЕМ автозагрузку - только по F1
    }

    private void InitializeManagers()
    {
        // Создаем все менеджеры
        GameState = new GameObject("GameState").AddComponent<GameState>();
        GameState.IsPlayerControlLocked = true;
        DontDestroyOnLoad(GameState.gameObject);


        ControlsController controlsController = new GameObject("ControlsController").AddComponent<ControlsController>();        //TODO: Set On Scene
        DontDestroyOnLoad(controlsController.gameObject);

        ResourceManager = new GameObject("ResourceManager").AddComponent<ResourceManager>();
        DontDestroyOnLoad(ResourceManager.gameObject);

        CameraController = FindFirstObjectByType<CameraController>();
        DontDestroyOnLoad(CameraController.gameObject);

        UI = FindFirstObjectByType<UIManager>();
        if (UI == null)
        {
            Debug.LogError("UIManager not found on scene! Please add UIManager component to a GameObject.");
            return;
        }
        UI.Initialize(); // Важно: инициализируем здесь!
        DontDestroyOnLoad(UI.gameObject);

        TextManager = new GameObject("TextManager").AddComponent<TextManager>();
        DontDestroyOnLoad(TextManager.gameObject);

        // Остальные менеджеры
        Loader = new ScriptLoader();
        SceneLoader = gameObject.AddComponent<SceneLoader>();
        VM = gameObject.AddComponent<ScriptVM>();
    }

    public void LoadScriptFromFile(string filePath)
    {
        string fullPath = Path.Combine(Application.streamingAssetsPath, filePath);

        if (File.Exists(fullPath))
        {
            byte[] scriptData = File.ReadAllBytes(fullPath);
            Script script = Loader.Load(scriptData);
            VM.LoadAndRunScript(script);
            Debug.Log($"Script loaded from: {fullPath}");
        }
        else
        {
            Debug.LogError($"File not found: {fullPath}");
        }
    }
   

    void Update()
    {
        // Загрузка скрипта только по F1
        if (Input.GetKeyDown(KeyCode.F1))
        {
            // Загружаем конкретный бинарный файл
            LoadScriptFromFile("Events/" + startScript + ".TRNSL");
        }

        // Для дебага
        if (Input.GetKeyDown(KeyCode.F2))
        {
            if (VM.IsRunning)
            {
                Debug.Log("Script is running");
            }
            else
            {
                Debug.Log("No script running");
            }
        }

        // Для остановки скрипта
        if (Input.GetKeyDown(KeyCode.F3))
        {
            // TODO: Добавить метод остановки в VM
            Debug.Log("Stop script requested");
        }
    }
}