using System.Text;

namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;

/// <summary>
/// Result of pre-deployment or on-demand validation with categorized errors and warnings.
/// </summary>
public sealed record ValidationResult
{
    /// <summary>True when there are no validation errors.</summary>
    public bool IsValid => Errors.Count == 0;
    /// <summary>Validation errors that block the operation.</summary>
    public IReadOnlyList<ValidationEntry> Errors { get; init; } = [];
    /// <summary>Non-blocking validation warnings.</summary>
    public IReadOnlyList<ValidationEntry> Warnings { get; init; } = [];

    /// <summary>
    /// Produces a compact, human-readable summary of the validation errors instead of a
    /// flat semicolon-joined dump. The old behaviour concatenated one clause
    /// per error — for an instance with 50–194 unbound attributes that is a wall of text
    /// unreadable in a CLI/UI toast. This groups errors by <see cref="ValidationCategory"/>
    /// and, within a category, rolls entries up by "module" (the entity's canonical name up
    /// to its last dot) with counts, capping the breadth with "… and N more". The full,
    /// per-entry list is still available on <see cref="Errors"/> for a detail view or log.
    /// </summary>
    /// <param name="maxGroups">
    /// Maximum number of modules (or messages, when entries are not entity-scoped) to list
    /// per category before collapsing the remainder into a "… and N more" suffix.
    /// </param>
    /// <returns>
    /// A multi-line summary, or an empty string when there are no errors. The first line is
    /// the total error count; subsequent lines are one per category.
    /// </returns>
    public string SummarizeErrors(int maxGroups = 6)
    {
        if (Errors.Count == 0)
            return string.Empty;

        var sb = new StringBuilder();
        sb.Append(Errors.Count).Append(Errors.Count == 1 ? " error:" : " errors:");

        // Group errors by category, preserving first-seen order for a stable rendering.
        var byCategory = new List<(ValidationCategory Category, List<ValidationEntry> Items)>();
        var categoryIndex = new Dictionary<ValidationCategory, int>();
        foreach (var error in Errors)
        {
            if (!categoryIndex.TryGetValue(error.Category, out var i))
            {
                i = byCategory.Count;
                categoryIndex[error.Category] = i;
                byCategory.Add((error.Category, []));
            }
            byCategory[i].Items.Add(error);
        }

        foreach (var (category, items) in byCategory)
        {
            sb.AppendLine();
            sb.Append("  • ").Append(category).Append(" (").Append(items.Count).Append("): ");

            // Prefer an entity/module rollup when every entry names an entity (the unbound-
            // binding case). Otherwise fall back to a capped list of the raw messages.
            if (items.TrueForAll(e => !string.IsNullOrEmpty(e.EntityName)))
            {
                var modules = new List<(string Module, int Count)>();
                var moduleIndex = new Dictionary<string, int>(StringComparer.Ordinal);
                foreach (var entry in items)
                {
                    var module = ModuleOf(entry.EntityName!);
                    if (!moduleIndex.TryGetValue(module, out var mi))
                    {
                        mi = modules.Count;
                        moduleIndex[module] = mi;
                        modules.Add((module, 0));
                    }
                    modules[mi] = (module, modules[mi].Count + 1);
                }

                var shown = modules.Take(maxGroups).Select(m => $"{m.Module} ({m.Count})");
                sb.Append(string.Join(", ", shown));
                if (modules.Count > maxGroups)
                    sb.Append($", … and {modules.Count - maxGroups} more module(s)");
            }
            else
            {
                var shown = items.Take(maxGroups).Select(e => e.Message);
                sb.Append(string.Join("; ", shown));
                if (items.Count > maxGroups)
                    sb.Append($"; … and {items.Count - maxGroups} more");
            }
        }

        return sb.ToString();
    }

    /// <summary>
    /// Returns the "module" portion of a canonical attribute name — everything up to the
    /// last <c>.</c> (e.g. <c>LeftReactorSide.LeakTest.DeltaVac</c> → <c>LeftReactorSide.LeakTest</c>).
    /// A name with no dot is reported under <c>(root)</c>.
    /// </summary>
    /// <param name="canonicalName">The entity's canonical name.</param>
    /// <returns>The module prefix, or <c>(root)</c> for top-level members.</returns>
    private static string ModuleOf(string canonicalName)
    {
        var lastDot = canonicalName.LastIndexOf('.');
        return lastDot > 0 ? canonicalName[..lastDot] : "(root)";
    }

    /// <summary>Returns a result with no errors or warnings.</summary>
    /// <returns>A <see cref="ValidationResult"/> with empty error and warning lists.</returns>
    public static ValidationResult Success() => new();

    /// <summary>Returns a result containing the given errors.</summary>
    /// <param name="errors">The validation errors to include.</param>
    /// <returns>A <see cref="ValidationResult"/> whose <see cref="Errors"/> list contains the supplied entries.</returns>
    public static ValidationResult FromErrors(params ValidationEntry[] errors) =>
        new() { Errors = errors };

    /// <summary>Merges multiple validation results into a single combined result.</summary>
    /// <param name="results">The results to merge.</param>
    /// <returns>A new <see cref="ValidationResult"/> with all errors and warnings from every supplied result combined.</returns>
    public static ValidationResult Merge(params ValidationResult[] results)
    {
        var errors = new List<ValidationEntry>();
        var warnings = new List<ValidationEntry>();
        foreach (var r in results)
        {
            errors.AddRange(r.Errors);
            warnings.AddRange(r.Warnings);
        }
        return new ValidationResult { Errors = errors, Warnings = warnings };
    }
}

/// <summary>
/// A single validation error or warning with category and context.
/// </summary>
public sealed record ValidationEntry
{
    /// <summary>The category classifying the kind of validation failure.</summary>
    public ValidationCategory Category { get; init; }
    /// <summary>Human-readable description of the validation issue.</summary>
    public string Message { get; init; } = string.Empty;

    /// <summary>
    /// The canonical name of the entity that caused the validation issue, if applicable.
    /// </summary>
    public string? EntityName { get; init; }

    /// <summary>Creates an error entry with the given category, message, and optional entity name.</summary>
    /// <param name="category">The validation category.</param>
    /// <param name="message">The error message.</param>
    /// <param name="entityName">The canonical name of the entity that caused the error, if any.</param>
    /// <returns>A new <see cref="ValidationEntry"/> representing an error.</returns>
    public static ValidationEntry Error(ValidationCategory category, string message, string? entityName = null) =>
        new() { Category = category, Message = message, EntityName = entityName };

    /// <summary>Creates a warning entry with the given category, message, and optional entity name.</summary>
    /// <param name="category">The validation category.</param>
    /// <param name="message">The warning message.</param>
    /// <param name="entityName">The canonical name of the entity that triggered the warning, if any.</param>
    /// <returns>A new <see cref="ValidationEntry"/> representing a warning.</returns>
    public static ValidationEntry Warning(ValidationCategory category, string message, string? entityName = null) =>
        new() { Category = category, Message = message, EntityName = entityName };
}

public enum ValidationCategory
{
    FlatteningFailure,
    NamingCollision,
    ScriptCompilation,
    AlarmTriggerReference,
    ScriptTriggerReference,
    ConnectionBinding,
    CallTargetNotFound,
    ParameterMismatch,
    ReturnTypeMismatch,
    TriggerOperandType,
    OnTriggerScriptNotFound,
    CrossCallViolation,
    MissingMetadata,
    ConnectionConfig,
    NativeAlarmSourceInvalid,

    /// <summary>
    /// A script/method parameter or return JSON Schema contains a
    /// <c>{"$ref":"lib:Name"}</c> reference that could not be resolved against the
    /// shared-schema library — dangling, cyclic, or over-depth. Deploy-blocking.
    /// </summary>
    SchemaReference
}
