using System.IO;
using System.Net.Http;
using gay.lilyy.LinkDownloader;
using nadena.dev.ndmf;
using UnityEditor;
using UnityEngine;

[assembly: ExportsPlugin(typeof(LinkDownloaderPlugin))]

namespace gay.lilyy.LinkDownloader
{
    public class LinkDownloaderPlugin : Plugin<LinkDownloaderPlugin>
    {
        public override string DisplayName => "LinkDownloader";
        public override string QualifiedName => "gay.lilyy.LinkDownloader";

        protected override void Configure()
        {
            InPhase(BuildPhase.Transforming).Run("LinkDownloader", async ctx =>
            {
                var links = ctx.AvatarRootObject.GetComponentsInChildren<LinkDownloaderConfig>();
                if (links.Length == 0) return;
                using var http = new HttpClient();
                foreach (var link in links) {
                    try
                    {
                        Debug.Log($"Downloading {link.link} to {link.path}");
                        var data = await http.GetByteArrayAsync(link.link);
                        File.WriteAllBytes(link.path, data);
                        Debug.Log($"Link saved to: {link.path}");
                    }
                    catch (System.Exception ex)
                    {
                        Debug.LogError($"Failed to download link: {ex.Message}");
                    }
                }
                AssetDatabase.Refresh();
            });
        }
    }
}
