using System;
using System.IO;

namespace AIRuntime.Runtime.Filesystem
{
    /// <summary>
    /// Represents the root directory AIRuntime is allowed to access.
    /// All filesystem operations are constrained to this workspace.
    /// </summary>
    public sealed class Workspace
    {
        private static readonly StringComparison PathComparison =
            Path.DirectorySeparatorChar == '\\'
                ? StringComparison.OrdinalIgnoreCase
                : StringComparison.Ordinal;

        /// <summary>
        /// Absolute path to the workspace root.
        /// </summary>
        public string Root { get; }

        public Workspace(string root)
        {
            if (string.IsNullOrWhiteSpace(root))
                throw new ArgumentException(nameof(root));

            Root = NormalizeRoot(root);

            Directory.CreateDirectory(Root);
        }

        /// <summary>
        /// Resolves a relative path against the workspace root.
        /// Throws if the resulting path escapes the workspace.
        /// </summary>
        public string Resolve(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentException(
                    "Path cannot be null or empty.",
                    nameof(path));

            if (Path.IsPathRooted(path))
                throw new UnauthorizedAccessException(
                    $"Path '{path}' must be relative to the workspace.");

            string fullPath = Path.GetFullPath(
                Path.Combine(Root, path));

            if (!IsInsideWorkspace(fullPath))
                throw new UnauthorizedAccessException(
                    $"Path '{path}' escapes the workspace.");

            EnsurePathDoesNotContainLinks(
                fullPath,
                path);

            return fullPath;
        }

        /// <summary>
        /// Returns true if the supplied path is inside the workspace.
        /// </summary>
        public bool IsInsideWorkspace(string fullPath)
        {
            if (string.IsNullOrWhiteSpace(fullPath) ||
                !Path.IsPathRooted(fullPath))
            {
                return false;
            }

            string normalizedPath;

            try
            {
                normalizedPath = Path.GetFullPath(fullPath);
            }
            catch (Exception exception)
                when (exception is ArgumentException ||
                      exception is NotSupportedException ||
                      exception is PathTooLongException)
            {
                return false;
            }

            return string.Equals(
                       normalizedPath,
                       Root,
                       PathComparison)
                   || normalizedPath.StartsWith(
                       AppendDirectorySeparator(Root),
                       PathComparison);
        }

        internal bool IsWorkspaceRoot(string fullPath)
        {
            return string.Equals(
                Path.GetFullPath(fullPath),
                Root,
                PathComparison);
        }

        private void EnsurePathDoesNotContainLinks(
            string fullPath,
            string requestedPath)
        {
            if (IsWorkspaceRoot(fullPath))
                return;

            string relativePath = fullPath
                .Substring(Root.Length)
                .TrimStart(
                    Path.DirectorySeparatorChar,
                    Path.AltDirectorySeparatorChar);

            string currentPath = Root;
            string[] segments = relativePath.Split(
                new[]
                {
                    Path.DirectorySeparatorChar,
                    Path.AltDirectorySeparatorChar
                },
                StringSplitOptions.RemoveEmptyEntries);

            foreach (string segment in segments)
            {
                currentPath = Path.Combine(
                    currentPath,
                    segment);

                FileAttributes attributes;

                try
                {
                    attributes = File.GetAttributes(
                        currentPath);
                }
                catch (FileNotFoundException)
                {
                    break;
                }
                catch (DirectoryNotFoundException)
                {
                    break;
                }

                if ((attributes & FileAttributes.ReparsePoint) != 0)
                {
                    throw new UnauthorizedAccessException(
                        $"Path '{requestedPath}' contains a symbolic link or directory junction.");
                }
            }
        }

        private static string NormalizeRoot(string root)
        {
            string fullPath = Path.GetFullPath(root);
            string pathRoot = Path.GetPathRoot(fullPath);

            if (string.Equals(
                    fullPath,
                    pathRoot,
                    PathComparison))
            {
                return fullPath;
            }

            return fullPath.TrimEnd(
                Path.DirectorySeparatorChar,
                Path.AltDirectorySeparatorChar);
        }

        private static string AppendDirectorySeparator(
            string path)
        {
            if (path.EndsWith(
                    Path.DirectorySeparatorChar.ToString(),
                    StringComparison.Ordinal) ||
                path.EndsWith(
                    Path.AltDirectorySeparatorChar.ToString(),
                    StringComparison.Ordinal))
            {
                return path;
            }

            return path + Path.DirectorySeparatorChar;
        }
    }
}
