namespace ReactorMaintenance.Simulation;

public sealed record JunctionFlow
{
    public float WeightFor(GridPosition outgoingBranch)
    {
        var index = IndexOfOutgoingBranch(outgoingBranch);
        if (index < 0)
            return 0;

        var weights = Balancing.Current.JunctionWeights(OutgoingBranches.Count, Prop.JunctionMode);
        return index < weights.Length ? weights[index] : 0;
    }

    private int IndexOfOutgoingBranch(GridPosition outgoingBranch)
    {
        for (var i = 0; i < OutgoingBranches.Count; i++)
        {
            if (OutgoingBranches[i] == outgoingBranch)
                return i;
        }

        return -1;
    }

    public GridPosition Position { get; init; } = new(0, 0);
    public PropState Prop { get; init; } = new();
    public ECarrierType Carrier { get; init; }
    public IReadOnlyList<GridPosition> Branches { get; init; } = Array.Empty<GridPosition>();
    public GridPosition? IncomingBranch { get; init; }
    public IReadOnlyList<GridPosition> OutgoingBranches { get; init; } = Array.Empty<GridPosition>();
    public IReadOnlyList<string> Errors { get; init; } = Array.Empty<string>();
    public bool IsValid => Errors.Count == 0;
}