using System;
using System.Threading;
using VehicleMotionControl.Primitives;

namespace MultiWheelC.Fleet;

public sealed partial class FleetRuntime
{
    private sealed record WriterRequest(FleetAutomaticWriter Writer, long Id, long StartRequestId);
    private FleetAutomaticWriter _automaticWriter;
    private FleetMotionCapabilitiesSnapshot _writerCapabilities;
    private WriterRequest _writerStartRequested, _writerStopRequested;
    private long _writerGeneration, _writerRequestSequence, _appliedWriterStartId, _appliedWriterStopId;
    private long _writerStopRequestId, _writerStopFollowerSequence;
    private Guid _writerSession, _writerStopSession;
    private bool _writerInputClosed, _writerAborted;
    private int _stopMotorSequence;
    private bool _stopFeedbackRequired, _stopFeedbackAdvanced;

    /// <summary>仅报告任务输出者的占用状态；停止操作或读取本属性均不会释放该占用。</summary>
    public bool HasAutomaticWriter
    {
        get { lock (_ownershipSync) return _automaticWriter != null; }
    }

    public FleetMotionCapabilitiesSnapshot CaptureMotionCapabilities()
    {
        lock (_ownershipSync)
        {
            RequireLeader();
            var layout = Layout ?? throw new InvalidOperationException("Establish the formation before reading its capabilities.");
            if (!_transport.TryGetReport(out var report) || report.MotionCapabilities == null)
                throw new InvalidOperationException("Fresh follower motion capabilities are required.");
            if (report.VehicleId != layout.FollowerVehicleId)
                throw new InvalidOperationException("Follower capability identity does not match the formation.");
            return new FleetMotionCapabilitiesSnapshot(layout, _pilot.ReadFleetMotionCapabilities(), report.MotionCapabilities);
        }
    }

    public FleetAutomaticWriter AcquireAutomaticWriter(string taskName) => AcquireAutomaticWriter(taskName, null);

    public FleetAutomaticWriter AcquireAutomaticWriter(string taskName, FleetMotionCapabilitiesSnapshot capabilities)
    {
        lock (_ownershipSync)
        {
            RequireLeader();
            if (string.IsNullOrWhiteSpace(taskName)) throw new ArgumentException("Task identity is required.", nameof(taskName));
            if (_automaticWriter != null || _layoutLease == null || Setup == null || _runEnded || _shutdownRequested ||
                _releaseOwnershipPending || _releaseLayoutRequested != 0 || _captureRequested != 0 ||
                _reestablishRequested != 0 || _startRequested != 0 || _stopRequested != 0 ||
                State is not (FleetRuntimeState.Idle or FleetRuntimeState.Stopped) || !IsStationary ||
                (_session != Guid.Empty && !IsStopConfirmed))
                throw new InvalidOperationException("A task writer requires the existing, stationary, unoccupied formation.");
            var current = CaptureMotionCapabilities();
            if (!_transport.TryGetReport(out var report) || !report.IsStationary)
                throw new InvalidOperationException("Both vehicles must be stationary before acquiring the task writer.");
            if (capabilities != null && !SameCapabilities(current, capabilities))
                throw new InvalidOperationException("Formation capabilities changed before acquiring the task writer.");
            _writerCapabilities = capabilities ?? current;
            _automaticWriter = new FleetAutomaticWriter(this, ++_writerGeneration, taskName, Setup);
            _writerStartRequested = _writerStopRequested = null;
            _appliedWriterStartId = _appliedWriterStopId = _writerStopRequestId = 0;
            _writerSession = _writerStopSession = Guid.Empty;
            _writerInputClosed = _writerAborted = false;
            return _automaticWriter;
        }
    }

    public long RequestStart(FleetAutomaticWriter writer)
    {
        lock (_ownershipSync)
        {
            RequireCurrentWriter(writer);
            if (_writerAborted) throw new InvalidOperationException("This task was stopped by a fault or global stop.");
            if (_writerStartRequested != null) return _writerStartRequested.Id;
            if (_writerStopRequested != null || State is not (FleetRuntimeState.Idle or FleetRuntimeState.Stopped) ||
                (_appliedWriterStartId != 0 && !WriterStopConfirmed()))
                throw new InvalidOperationException("Confirm the previous phase stop before starting another phase.");
            ValidateWriterCapabilities();
            var request = new WriterRequest(writer, ++_writerRequestSequence, 0);
            _writerStartRequested = request;
            _writerStopRequestId = _appliedWriterStopId = 0;
            _writerInputClosed = true; // No output until this request has been consumed.
            _startRequested = (int)FleetInputSource.Automatic + 1;
            return request.Id;
        }
    }

    public void SubmitVelocity(FleetAutomaticWriter writer, Twist2D velocity, long expectedStartRequestId = 0)
    {
        lock (_ownershipSync)
        {
            RequireCurrentWriter(writer);
            if (_writerInputClosed || _writerAborted || _writerStartRequested != null || _appliedWriterStartId == 0 ||
                _writerSession != _session || (expectedStartRequestId != 0 && expectedStartRequestId != _appliedWriterStartId))
                throw new InvalidOperationException("The task phase is not accepting velocity requests.");
            Volatile.Write(ref _automaticRequest,
                new VelocityRequest(velocity, _clock.GetTimestamp(), writer, _appliedWriterStartId));
        }
    }

    // A stale task/phase finally is an idempotent no-op, never a stop for its successor.
    public long RequestStop(FleetAutomaticWriter writer, long expectedStartRequestId = 0)
    {
        lock (_ownershipSync)
        {
            if (!IsCurrentWriter(writer)) return 0;
            var phase = _writerStartRequested?.Id ?? _appliedWriterStartId;
            if (expectedStartRequestId != 0 && expectedStartRequestId != phase) return 0;
            if (_writerStopRequestId != 0) return _writerStopRequestId;
            _writerInputClosed = true;
            _writerStartRequested = null;
            _startRequested = 0;
            Volatile.Write(ref _automaticRequest, null);
            _writerStopRequestId = ++_writerRequestSequence;
            _writerStopRequested = new WriterRequest(writer, _writerStopRequestId, phase);
            return _writerStopRequestId;
        }
    }

    /// <summary>显式请求全局停止，与匿名实验的清理操作分开；不解除编队。</summary>
    public void RequestGlobalStop()
    {
        lock (_ownershipSync)
        {
            if (_automaticWriter != null)
            {
                if (RequestStop(_automaticWriter) == 0) _stopRequested = 1;
                _writerAborted = true;
            }
            else _stopRequested = 1;
        }
    }

    public FleetExecutionSnapshot ReadExecutionSnapshot(FleetAutomaticWriter writer)
    {
        lock (_ownershipSync)
        {
            if (writer == null) throw new ArgumentNullException(nameof(writer));
            var current = IsCurrentWriter(writer);
            var motionAllowed = current && !_writerInputClosed && !_writerAborted &&
                _writerSession == _session && State == FleetRuntimeState.Driving && _releaseCommandSequence < 0 &&
                _transport.TryGetReport(out var report) && report.SessionId == _session &&
                report.Ready && report.PreparedMotionRevision == _revision && report.Fault.Length == 0;
            return new FleetExecutionSnapshot(writer.WriterId, writer.Generation, writer.Setup,
                current ? _session : Guid.Empty, State, current ? _revision : 0,
                current ? _appliedWriterStartId : 0, current ? _appliedWriterStopId : 0,
                current && WriterStopConfirmed(), LastError, ObservationPauseReason, current, motionAllowed)
            { StopRevision = current ? _stopRevision : 0, StopCommandSequence = current ? _stopCommandSequence : 0 };
        }
    }

    public bool TryReleaseAutomaticWriter(FleetAutomaticWriter writer)
    {
        lock (_ownershipSync)
        {
            if (!IsCurrentWriter(writer) || !WriterStopConfirmed()) return false;
            _automaticWriter = null;
            _writerCapabilities = null;
            _writerStartRequested = _writerStopRequested = null;
            Volatile.Write(ref _automaticRequest, null);
            return true;
        }
    }

    private bool IsCurrentWriter(FleetAutomaticWriter writer) => writer != null &&
        ReferenceEquals(_automaticWriter, writer) && ReferenceEquals(writer.Runtime, this) &&
        ReferenceEquals(writer.Setup, Setup) && ReferenceEquals(_pilot.MotionChassis, _chassis) &&
        _layoutLease != null && !_releaseOwnershipPending && !_runEnded && !_shutdownRequested;

    private void RequireCurrentWriter(FleetAutomaticWriter writer)
    {
        RequireLeader();
        if (!IsCurrentWriter(writer)) throw new InvalidOperationException("The Fleet task writer is no longer current.");
    }

    private void RequireAnonymousWriter()
    {
        if (_automaticWriter != null) throw new InvalidOperationException("A formal Fleet task owns the automatic output.");
    }

    private bool ConsumeWriterStop()
    {
        var request = _writerStopRequested;
        if (request == null) return false;
        _writerStopRequested = null;
        if (!IsCurrentWriter(request.Writer)) return false;
        _appliedWriterStopId = request.Id;
        _writerStopSession = _session;
        _writerStopFollowerSequence = _transport.TryGetReport(out var report) ? report.Sequence : 0;
        _stopCommandSequence = 0;
        StopSession("", newStopEvidence: true);
        return true;
    }

    private bool WriterStopConfirmed()
    {
        if (_appliedWriterStopId == 0 || _writerStopRequested != null || _writerStartRequested != null ||
            _writerStopSession != _session || !HasStopStandstill() ||
            !_transport.TryGetReport(out var report) || report.Sequence <= _writerStopFollowerSequence ||
            report.SessionId != _session || !report.IsStationary || report.Fault.Length != 0) return false;
        // A task cancelled before its first start never had a command session to stop.
        return _session == Guid.Empty ? State == FleetRuntimeState.Stopped : IsStopConfirmed;
    }

    private void BeginStopFeedback()
    {
        _stopMotorSequence = Volatile.Read(ref _pilot.ActualBodyVelocitySequence);
        _stopFeedbackRequired = true;
        _stopFeedbackAdvanced = false;
    }

    private bool HasStopStandstill()
    {
        if (!_stopFeedbackRequired) return IsStationary;
        var sequence = Volatile.Read(ref _pilot.ActualBodyVelocitySequence);
        if (sequence != 0 && sequence != _stopMotorSequence) _stopFeedbackAdvanced = true;
        return _stopFeedbackAdvanced && IsStationary;
    }

    private void ValidateWriterCapabilities()
    {
        if (_automaticWriter == null) return;
        RequireCurrentWriter(_automaticWriter);
        var local = _pilot.ReadFleetMotionCapabilities();
        if (!SameCapabilities(local, _writerCapabilities.Leader))
            throw new InvalidOperationException("Leader motion configuration changed during the Fleet task.");
        if (_transport.TryGetReport(out var report) &&
            (report.MotionCapabilities == null || !SameCapabilities(report.MotionCapabilities, _writerCapabilities.Follower)))
            throw new InvalidOperationException("Follower motion configuration changed during the Fleet task.");
    }

    private static bool SameCapabilities(FleetMotionCapabilitiesSnapshot a, FleetMotionCapabilitiesSnapshot b) =>
        a.Layout.LeaderVehicleId == b.Layout.LeaderVehicleId && a.Layout.FollowerVehicleId == b.Layout.FollowerVehicleId &&
        a.Layout.LeaderPoseInFleet.Equals(b.Layout.LeaderPoseInFleet) && a.Layout.FollowerPoseInFleet.Equals(b.Layout.FollowerPoseInFleet) &&
        SameCapabilities(a.Leader, b.Leader) && SameCapabilities(a.Follower, b.Follower);

    private static bool SameCapabilities(FleetMotionCapabilities a, FleetMotionCapabilities b) => a != null && b != null &&
        a.VehicleId == b.VehicleId && a.ConfigurationVersion == b.ConfigurationVersion &&
        FleetMotionCapabilities.Create(a.VehicleId, a.Wheels, a.MaximumLinearAccelerationMetersPerSecondSquared,
            a.MaximumLinearDecelerationMetersPerSecondSquared).ConfigurationVersion ==
        FleetMotionCapabilities.Create(b.VehicleId, b.Wheels, b.MaximumLinearAccelerationMetersPerSecondSquared,
            b.MaximumLinearDecelerationMetersPerSecondSquared).ConfigurationVersion;
}
