using System.IO;
using System.Linq;
using UnityEngine;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace LLM.Editor.Analysis
{
    /// <summary>
    /// Provides a list of all packages currently installed in the project
    /// by reading the package manifest and lock files.
    /// </summary>
    public class PackageManagerProvider : IContextProvider
    {
        private class ManifestFile
        {
            public Dictionary<string, string> dependencies;
        }

        private class LockFile
        {
            public Dictionary<string, PackageLock> dependencies;
        }

        private class PackageLock
        {
            public string version;
            public int depth;
            public string source;
        }

        public class PackageInfo
        {
            public string name;
            public string version;
            public string source;
        }

        public object GetContext(Object target, string qualifier)
        {
            var lockJsonPath = Path.Combine(Application.dataPath, "..", "Packages", "packages-lock.json");
            var manifestJsonPath = Path.Combine(Application.dataPath, "..", "Packages", "manifest.json");

            if (File.Exists(lockJsonPath))
            {
                try
                {
                    var json = File.ReadAllText(lockJsonPath);
                    var lockFile = JsonConvert.DeserializeObject<LockFile>(json);
                    var packages = lockFile.dependencies.Select(kvp => new PackageInfo
                    {
                        name = kvp.Key,
                        version = kvp.Value.version,
                        source = kvp.Value.source
                    }).ToList();
                    return packages;
                }
                catch (System.Exception e)
                {
                    return $"Error parsing packages-lock.json: {e.Message}";
                }
            }

            if (File.Exists(manifestJsonPath))
            {
                try
                {
                    var json = File.ReadAllText(manifestJsonPath);
                    var manifestFile = JsonConvert.DeserializeObject<ManifestFile>(json);
                    var packages = manifestFile.dependencies.Select(kvp => new PackageInfo
                    {
                        name = kvp.Key,
                        version = kvp.Value,
                        source = "manifest"
                    }).ToList();
                    return packages;
                }
                catch (System.Exception e)
                {
                    return $"Error parsing manifest.json: {e.Message}";
                }
            }

            return "Error: Could not find 'packages-lock.json' or 'manifest.json' in the Packages folder.";
        }
    }
}