using System;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using Supabase.Gotrue;
using Supabase.Gotrue.Exceptions;
using Client = Supabase.Client;
using Cysharp.Threading.Tasks;

namespace GhostSystem
{
    public class SupabaseManager : MonoBehaviour
    {
        public static SupabaseManager instance { get; private set; }

        public const string subabaseUrl = "https://cezghxztvyggwgunyhmq.supabase.co";
        public const string supabaseAnonKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImNlemdoeHp0dnlnZ3dndW55aG1xIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDcyMTk5MzcsImV4cCI6MjA2Mjc5NTkzN30.vr6-3X3Ux_DjcCiw_CqG-VKP8BiBXtmCzAXjYTiA_vY";

        public Client supabase { get; private set; }
        public string userId => supabase?.Auth?.CurrentUser?.Id;

        private string email;
        private string password;
        private const string authFileName = "auth.txt";

        public static event Action OnSuperbaseReady;

        private void Start()
        {
            Initialize().Forget();
        }


        private async UniTask Initialize()
        {
            if (instance == null)
            {
                instance = this;
                DontDestroyOnLoad(gameObject);
            }
            else
            {
                Destroy(gameObject);
                return;
            }

            Debug.Log("🌐 Starting Supabase setup...");
            await RunDiagnostics();

            await InitSupabaseAsync();
            OnSuperbaseReady?.Invoke();
        }

        private async UniTask InitSupabaseAsync()
        {
            if (supabase != null)
                return;

            string path = Path.Combine(Application.persistentDataPath, authFileName);

            if (File.Exists(path))
            {
                string[] lines = await UniTask.Run(() => File.ReadAllLines(path));
                email = lines[0];
                password = lines[1];
            }
            else
            {
                email = string.IsNullOrEmpty(SystemInfo.deviceUniqueIdentifier)
                    ? $"{Guid.NewGuid()}@device.local"
                    : $"{SystemInfo.deviceUniqueIdentifier}@device.local";

                password = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

                await UniTask.Run(() => File.WriteAllLines(path, new[] { email, password }));
            }

            Debug.Log($"📧 Using Email: {email}, Password: {password}");

            supabase = new Client(subabaseUrl, supabaseAnonKey);

            try
            {
                await supabase.InitializeAsync();
                Debug.Log("✅ Supabase initialized.");
            }
            catch (Exception ex)
            {
                Debug.LogError($"❌ Initialization failed: {ex}");
            }

            await AuthenticateAsync(email, password);
            Debug.Log($"👤 Authenticated user ID: {userId}");
        }

        public async UniTask AuthenticateAsync(string email, string password)
        {
            try
            {
                await supabase.Auth.SignIn(email, password);
                Debug.Log("🔓 Sign-in successful");
            }
            catch (Exception authEx)
            {
                Debug.LogWarning($"Sign-in failed, trying sign-up: {authEx.Message}");
                try
                {
                    await supabase.Auth.SignUp(email, password);
                    Debug.Log("🆕 Sign-up successful");
                }
                catch (Exception ex)
                {
                    Debug.LogError($"❌ Authentication failed: {ex}");
                }
            }
        }

        private async UniTask RunDiagnostics()
        {
            await UniTask.WhenAll(CheckSupabaseHealthAsync(), CheckGoogleConnectionAsync());
        }

        private async UniTask CheckSupabaseHealthAsync()
        {
            using var www = UnityWebRequest.Get($"{subabaseUrl}/auth/v1/health");
            www.SetRequestHeader("apikey", supabaseAnonKey);
            await www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.Success)
                Debug.Log($"✅ Supabase health: {www.downloadHandler.text}");
            else
                Debug.LogError($"❌ Supabase health check failed: {www.error}");
        }

        private async UniTask CheckGoogleConnectionAsync()
        {
            using var www = UnityWebRequest.Get("https://www.google.com");
            await www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.Success)
                Debug.Log("✅ Google request succeeded.");
            else
                Debug.LogError($"❌ Google connection failed: {www.error}");
        }
    }
}
