You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: bundle.go
    path of file: ./repos/tidb/pkg/ddl/placement
    
    the code of the file until where you have to start completion: // Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package placement

import (
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"slices"
	"sort"
	"strconv"
	"strings"

	"github.com/pingcap/failpoint"
	"github.com/pingcap/tidb/pkg/parser/model"
	"github.com/pingcap/tidb/pkg/tablecodec"
	"github.com/pingcap/tidb/pkg/util/codec"
	pd "github.com/tikv/pd/client/http"
	"gopkg.in/yaml.v2"
)

// Bundle is a group of all rules and configurations. It is used to support rule cache.
// Alias `pd.GroupBundle` is to wrap more methods.
type Bundle pd.GroupBundle

// NewBundle will create a bundle with the provided ID.
// Note that you should never pass negative id.
func NewBundle(id int64) *Bundle {
	return &Bundle{
		ID: GroupID(id),
	}
}

// NewBundleFromConstraintsOptions will transform constraints options into the bundle.
func NewBundleFromConstraintsOptions(options *model.PlacementSettings) (*Bundle, error) {
	if options == nil {
		return nil, fmt.Errorf("%w: options can not be nil", ErrInvalidPlacementOptions)
	}

	if len(options.PrimaryRegion) > 0 || len(options.Regions) > 0 || len(options.Schedule) > 0 {
		return nil, fmt.Errorf("%w: should be [LEADER/VOTER/LEARNER/FOLLOWER]_CONSTRAINTS=.. [VOTERS/FOLLOWERS/LEARNERS]=.., mixed other sugar options %s", ErrInvalidPlacementOptions, options)
	}

	constraints := options.Constraints
	leaderConst := options.LeaderConstraints
	learnerConstraints := options.LearnerConstraints
	followerConstraints := options.FollowerConstraints
	explicitFollowerCount := options.Followers
	explicitLearnerCount := options.Learners

	rules := []*pd.Rule{}
	commonConstraints, err := NewConstraintsFromYaml([]byte(constraints))
	if err != nil {
		// If it's not in array format, attempt to parse it as a dictionary for more detailed definitions.
		// The dictionary format specifies details for each replica. Cons
    
func NewBundleFromConstraintsOptions(options *model.PlacementSettings) (*Bundle, error) {
	if options == nil {
		return nil, fmt.Errorf("%w: options can not be nil", ErrInvalidPlacementOptions)
	}

	if len(options.PrimaryRegion) > 0 || len(options.Regions) > 0 || len(options.Schedule) > 0 {
		return nil, fmt.Errorf("%w: should be [LEADER/VOTER/LEARNER/FOLLOWER]_CONSTRAINTS=.. [VOTERS/FOLLOWERS/LEARNERS]=.., mixed other sugar options %s", ErrInvalidPlacementOptions, options)
	}

	constraints := options.Constraints
	leaderConst := options.LeaderConstraints
	learnerConstraints := options.LearnerConstraints
	followerConstraints := options.FollowerConstraints
	explicitFollowerCount := options.Followers
	explicitLearnerCount := options.Learners

	rules := []*pd.Rule{}
	commonConstraints, err := NewConstraintsFromYaml([]byte(constraints))
	if err != nil {
		// If it's not in array format, attempt to parse it as a dictionary for more detailed definitions.
		// The dictionary format specifies details for each replica. Constraints are used to define normal
		// replicas that should act as voters.
		// For example: CONSTRAINTS='{ "+region=us-east-1":2, "+region=us-east-2": 2, "+region=us-west-1": 1}'
		normalReplicasRules, err := NewRuleBuilder().
			SetRole(pd.Voter).
			SetConstraintStr(constraints).
			BuildRulesWithDictConstraintsOnly()
		if err != nil {
			return nil, err
		}
		rules = append(rules, normalReplicasRules...)
	}
	needCreateDefault := len(rules) == 0
	leaderConstraints, err := NewConstraintsFromYaml([]byte(leaderConst))
	if err != nil {
		return nil, fmt.Errorf("%w: 'LeaderConstraints' should be [constraint1, ...] or any yaml compatible array representation", err)
	}
	for _, cnst := range commonConstraints {
		if err := AddConstraint(&leaderConstraints, cnst); err != nil {
			return nil, fmt.Errorf("%w: LeaderConstraints conflicts with Constraints", err)
		}
	}
	leaderReplicas, followerReplicas := uint64(1), uint64(2)
	if explicitFollowerCount > 0 {
		followerReplicas = explicitFollowerCount
	}
	if !needCreateDefault {
		if len(leaderConst) == 0 {
			leaderReplicas = 0
		}
		if len(followerConstraints) == 0 {
			if explicitFollowerCount > 0 {
				return nil, fmt.Errorf("%w: specify follower count without specify follower constraints when specify other constraints", ErrInvalidPlacementOptions)
			}
			followerReplicas = 0
		}
	}

	// create leader rule.
	// if no constraints, we need create default leader rule.
	if leaderReplicas > 0 {
		leaderRule := NewRule(pd.Leader, leaderReplicas, leaderConstraints)
		rules = append(rules, leaderRule)
	}

	// create follower rules.
	// if no constraints, we need create default follower rules.
	if followerReplicas > 0 {
		builder := NewRuleBuilder().
			SetRole(pd.Voter).
			SetReplicasNum(followerReplicas).
			SetSkipCheckReplicasConsistent(needCreateDefault && (explicitFollowerCount == 0)).
			SetConstraintStr(followerConstraints)
		followerRules, err := builder.BuildRules()
		if err != nil {
			return nil, fmt.Errorf("%w: invalid FollowerConstraints", err)
		}
		for _, followerRule := range followerRules {
			for _, cnst := range commonConstraints {
				if err := AddConstraint(&followerRule.LabelConstraints, cnst); err != nil {
					return nil, fmt.Errorf("%w: FollowerConstraints conflicts with Constraints", err)
				}
			}
		}
		rules = append(rules, followerRules...)
	}

	// create learner rules.
	builder := NewRuleBuilder().
		SetRole(pd.Learner).
		SetReplicasNum(explicitLearnerCount).
		SetConstraintStr(learnerConstraints)
	learnerRules, err := builder.BuildRules()
	if err != nil {
		return nil, fmt.Errorf("%w: invalid LearnerConstraints", err)
	}
	for _, rule := range learnerRules {
		for _, cnst := range commonConstraints {
			if err := AddConstraint(&rule.LabelConstraints, cnst); err != nil {
				return nil, fmt.Errorf("%w: LearnerConstraints conflicts with Constraints", err)
			}
		}
	}
	rules = append(rules, learnerRules...)
	labels, err := newLocationLabelsFromSurvivalPreferences(options.SurvivalPreferences)
	if err != nil {
		return nil, err
	}
	for _, rule := range rules {
		rule.LocationLabels = labels
	}
	return &Bundle{Rules: rules}, nil
}