using System.Text.Json;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;

namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;

/// <summary>
///     v3 Batch 4 (Wave-B review recommendation) — the artifact-decode seam
///     (<see cref="DeploymentArtifact.ParseComposition(System.ReadOnlySpan{byte})"/>) and the live compose seam
///     (<see cref="AddressSpaceComposer.Compose"/>) must produce BYTE-IDENTICAL <b>Raw</b> and <b>UNS</b> node
///     sets for the same seeded config. This is the guard that a future artifact-decode drift can't silently
///     diverge the deployed dual-namespace address space from what was authored/validated. The existing
///     <c>DeploymentArtifactEquipRefParityTests</c> covers <c>{{equip}}</c> script-path parity; this covers the
///     RawContainers / RawTags / UnsReferenceVariables sets (RawPaths, UNS NodeIds, Organizes backing paths,
///     writable + historian + array shape).
/// </summary>
public sealed class DeploymentArtifactRawUnsParityTests
{
    [Fact]
    public void Raw_and_uns_node_sets_are_byte_parity_between_compose_and_artifact_decode()
    {
        // Entity-side config: folder → driver → device → group → 4 tags, an area/line/equipment, and a UNS
        // reference with a display-name override. The four tags cover every per-field intent RawTagPlan
        // carries: historize (+ tagname override), plain read-only, ARRAY (isArray + arrayLength), and
        // NATIVE ALARM (a TagConfig.alarm object → EquipmentTagAlarmInfo).
        //
        // The array and alarm tags were folded in here when the three placeholder suites
        // (DeploymentArtifact{Array,Historize,Alias}ParityTests) were deleted — they had been parked on
        // "unskip when Batch 4 lights the equipment-tag plans", but Batch 4 RETIRED equipment-tag plans
        // instead of lighting them, so their subject moved onto the raw tag and belongs in this comparison.
        var folder = new RawFolder { RawFolderId = "fld-1", ClusterId = "c1", Name = "Cell1", ParentRawFolderId = null };
        var driver = new DriverInstance { DriverInstanceId = "drv-1", ClusterId = "c1", Name = "Modbus", DriverType = "Modbus", DriverConfig = "{}", RawFolderId = "fld-1" };
        var device = new Device { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = "Dev1", DeviceConfig = "{}" };
        var group = new TagGroup { TagGroupId = "grp-1", DeviceId = "dev-1", Name = "Fast", ParentTagGroupId = null };
        var speed = new Tag
        {
            TagId = "tag-speed", DeviceId = "dev-1", TagGroupId = "grp-1", Name = "Speed", DataType = "Float",
            AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{\"isHistorized\":true,\"historianTagname\":\"WW.Speed\"}",
        };
        var run = new Tag
        {
            TagId = "tag-run", DeviceId = "dev-1", TagGroupId = null, Name = "Run", DataType = "Boolean",
            AccessLevel = TagAccessLevel.Read, TagConfig = "{}",
        };
        var profile = new Tag
        {
            TagId = "tag-profile", DeviceId = "dev-1", TagGroupId = "grp-1", Name = "Profile", DataType = "Float",
            AccessLevel = TagAccessLevel.Read, TagConfig = "{\"isArray\":true,\"arrayLength\":16}",
        };
        var tempHi = new Tag
        {
            TagId = "tag-temphi", DeviceId = "dev-1", TagGroupId = null, Name = "TempHi", DataType = "Boolean",
            AccessLevel = TagAccessLevel.ReadWrite,
            TagConfig = "{\"alarm\":{\"alarmType\":\"OffNormalAlarm\",\"severity\":700}}",
        };
        var area = new UnsArea { UnsAreaId = "a1", ClusterId = "c1", Name = "filling" };
        var line = new UnsLine { UnsLineId = "l1", UnsAreaId = "a1", Name = "line1" };
        var equip = new Equipment { EquipmentId = "EQ-1", UnsLineId = "l1", Name = "station1", MachineCode = "M1" };
        var reference = new UnsTagReference { UnsTagReferenceId = "ref-1", EquipmentId = "EQ-1", TagId = "tag-speed", DisplayNameOverride = "MotorSpeed" };

        var composed = AddressSpaceComposer.Compose(
            new[] { area }, new[] { line }, new[] { equip },
            new[] { driver }, Array.Empty<ScriptedAlarm>(),
            unsTagReferences: new[] { reference }, tags: new[] { speed, run, profile, tempHi },
            rawFolders: new[] { folder }, devices: new[] { device }, tagGroups: new[] { group });

        // Artifact JSON — the same shape ConfigComposer serializes (enums numeric: ReadWrite = 1, Read = 0).
        var blob = JsonSerializer.SerializeToUtf8Bytes(new
        {
            RawFolders = new[] { new { RawFolderId = "fld-1", ParentRawFolderId = (string?)null, Name = "Cell1", ClusterId = "c1" } },
            DriverInstances = new[] { new { DriverInstanceId = "drv-1", DriverType = "Modbus", DriverConfig = "{}", Name = "Modbus", RawFolderId = "fld-1", ClusterId = "c1" } },
            Devices = new[] { new { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = "Dev1", DeviceConfig = "{}" } },
            TagGroups = new[] { new { TagGroupId = "grp-1", ParentTagGroupId = (string?)null, DeviceId = "dev-1", Name = "Fast" } },
            Tags = new object[]
            {
                new { TagId = "tag-speed", DeviceId = "dev-1", TagGroupId = "grp-1", Name = "Speed", DataType = "Float", AccessLevel = 1, TagConfig = "{\"isHistorized\":true,\"historianTagname\":\"WW.Speed\"}" },
                new { TagId = "tag-run", DeviceId = "dev-1", TagGroupId = (string?)null, Name = "Run", DataType = "Boolean", AccessLevel = 0, TagConfig = "{}" },
                new { TagId = "tag-profile", DeviceId = "dev-1", TagGroupId = "grp-1", Name = "Profile", DataType = "Float", AccessLevel = 0, TagConfig = "{\"isArray\":true,\"arrayLength\":16}" },
                new { TagId = "tag-temphi", DeviceId = "dev-1", TagGroupId = (string?)null, Name = "TempHi", DataType = "Boolean", AccessLevel = 1, TagConfig = "{\"alarm\":{\"alarmType\":\"OffNormalAlarm\",\"severity\":700}}" },
            },
            UnsAreas = new[] { new { UnsAreaId = "a1", Name = "filling", ClusterId = "c1" } },
            UnsLines = new[] { new { UnsLineId = "l1", UnsAreaId = "a1", Name = "line1" } },
            Equipment = new[] { new { EquipmentId = "EQ-1", UnsLineId = "l1", Name = "station1", MachineCode = "M1" } },
            UnsTagReferences = new[] { new { UnsTagReferenceId = "ref-1", EquipmentId = "EQ-1", TagId = "tag-speed", DisplayNameOverride = "MotorSpeed" } },
        });

        var decoded = DeploymentArtifact.ParseComposition(blob);

        // Sanity: the sets are non-empty (all four raw tags + the projected UNS variable materialised).
        composed.RawTags.Count.ShouldBe(4);

        // Sanity on the two folded-in branches — without these, a composer that dropped array/alarm intent
        // ENTIRELY would still pass the parity assertion below, because the artifact decode would drop it too
        // and the two empties would compare equal. Parity alone cannot tell "both right" from "both blind".
        var composedArray = composed.RawTags.Single(t => t.Name == "Profile");
        composedArray.IsArray.ShouldBeTrue();
        composedArray.ArrayLength.ShouldBe(16u);
        var composedAlarm = composed.RawTags.Single(t => t.Name == "TempHi");
        composedAlarm.Alarm.ShouldNotBeNull();
        composedAlarm.Alarm!.AlarmType.ShouldBe("OffNormalAlarm");
        composedAlarm.Writable.ShouldBeTrue();
        composed.UnsReferenceVariables.Count.ShouldBe(1);
        composed.UnsReferenceVariables[0].NodeId.ShouldBe("filling/line1/station1/MotorSpeed");
        composed.UnsReferenceVariables[0].BackingRawPath.ShouldBe("Cell1/Modbus/Dev1/Fast/Speed");

        // Byte-parity: the three dual-namespace node sets are record-equal between the two seams.
        decoded.RawContainers.ShouldBe(composed.RawContainers);
        decoded.RawTags.ShouldBe(composed.RawTags);
        decoded.UnsReferenceVariables.ShouldBe(composed.UnsReferenceVariables);
    }
}
