// Copyright 2020-2026 Buf Technologies, 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 bufprint

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	"github.com/bufbuild/buf/private/pkg/protostat"
)

type statsPrinter struct {
	writer io.Writer
}

func newStatsPrinter(writer io.Writer) *statsPrinter {
	return &statsPrinter{
		writer: writer,
	}
}

func (p *statsPrinter) PrintStats(ctx context.Context, format Format, stats *protostat.Stats) error {
	switch format {
	case FormatText:
		_, err := fmt.Fprintf(
			p.writer,
			`Files:               %d
Types:               %d
Packages:            %d
Messages:            %d
Deprecated Messages: %d
Fields:              %d
Enums:               %d
Deprecated Enums:    %d
Enum Values:         %d
Services:            %d
RPCs:                %d
Deprecated RPCs:     %d
Extensions:          %d
`,

			stats.Files,
			stats.Types,
			stats.Packages,
			stats.Messages,
			stats.DeprecatedMessages,
			stats.Fields,
			stats.Enums,
			stats.DeprecatedEnums,
			stats.EnumValues,
			stats.Services,
			stats.RPCs,
			stats.DeprecatedRPCs,
			stats.Extensions,
		)
		return err
	case FormatJSON:
		return json.NewEncoder(p.writer).Encode(stats)
	default:
		return fmt.Errorf("unknown format: %v", format)
	}
}
