// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// 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 log

import "fmt"

// OtlpAdder persists a single OTLP record into the backing store.
// Parameters: entryType ("trace"/"metrics"/"log"), message (JSON payload),
// clientIp and userAgent from the originating HTTP request.
// The unique entry name is generated by the implementation.
type OtlpAdder func(entryType, message, clientIp, userAgent string) error

// OpenClawProvider receives OpenTelemetry data pushed by an OpenClaw agent over
// HTTP and persists each record as an Entry row via the OtlpAdder supplied at
// construction time. It is passive (push-based via HTTP): Start/Stop are no-ops
// and Write is not applicable.
type OpenClawProvider struct {
	providerName string
	addOtlpEntry OtlpAdder
}

// NewOpenClawProvider creates an OpenClawProvider backed by addOtlpEntry.
func NewOpenClawProvider(providerName string, addOtlpEntry OtlpAdder) *OpenClawProvider {
	return &OpenClawProvider{providerName: providerName, addOtlpEntry: addOtlpEntry}
}

// Write is not applicable for an HTTP-push provider and always returns an error.
func (p *OpenClawProvider) Write(_, _ string) error {
	return fmt.Errorf("OpenClawProvider receives data over HTTP and does not accept Write calls")
}

// Start is a no-op; OpenClawProvider is passive and has no background goroutine.
func (p *OpenClawProvider) Start(_ EntryAdder, _ func(error)) error { return nil }

// Stop is a no-op.
func (p *OpenClawProvider) Stop() error { return nil }

// AddTrace persists an OTLP trace payload (already serialised to JSON).
func (p *OpenClawProvider) AddTrace(message []byte, clientIp, userAgent string) error {
	return p.addOtlpEntry("trace", string(message), clientIp, userAgent)
}

// AddMetrics persists an OTLP metrics payload (already serialised to JSON).
func (p *OpenClawProvider) AddMetrics(message []byte, clientIp, userAgent string) error {
	return p.addOtlpEntry("metrics", string(message), clientIp, userAgent)
}

// AddLogs persists an OTLP logs payload (already serialised to JSON).
func (p *OpenClawProvider) AddLogs(message []byte, clientIp, userAgent string) error {
	return p.addOtlpEntry("log", string(message), clientIp, userAgent)
}
