using System.Globalization;

namespace YMhut.Box.Core.App;

public sealed record InstallRootContext(
    string InstallRoot,
    string AssetsRoot,
    string ManifestPath,
    string ManifestIdentity,
    bool IsPackaged,
    string ResolvedFrom)
{
    public string InstallIdentity { get; init; } = BuildInstallIdentity(InstallRoot, ManifestIdentity);

    public string CheckBasis => $"installRoot={InstallRoot}; manifest={ManifestIdentity}; source={ResolvedFrom}";

    public static string BuildInstallIdentity(string installRoot, string manifestIdentity)
        => $"{NormalizePath(installRoot)}|{manifestIdentity}";

    public static string BuildManifestIdentity(string installRoot)
    {
        var manifestPath = Path.Combine(installRoot, InstallManifest.RelativePath.Replace('/', Path.DirectorySeparatorChar));
        if (!File.Exists(manifestPath))
        {
            return $"no-manifest:{NormalizePath(installRoot)}";
        }

        try
        {
            var info = new FileInfo(manifestPath);
            var manifest = InstallManifest.Parse(File.ReadAllText(manifestPath));
            var release = manifest.Release is null
                ? "unknown"
                : $"{manifest.Release.Version}/{manifest.Release.Build}/{manifest.Release.Channel}/{manifest.Release.PackageVersion}";
            return $"{release}:{info.Length}:{info.LastWriteTimeUtc.Ticks.ToString(CultureInfo.InvariantCulture)}";
        }
        catch
        {
            return $"invalid-manifest:{NormalizePath(manifestPath)}";
        }
    }

    private static string NormalizePath(string path)
    {
        try
        {
            return Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
        }
        catch
        {
            return path.Trim();
        }
    }
}
