package conversion

import "fmt"

// ErrorCode 错误码枚举
type ErrorCode string

const (
	ErrorCodeInvalidInput          ErrorCode = "INVALID_INPUT"
	ErrorCodeMissingRequiredField  ErrorCode = "MISSING_REQUIRED_FIELD"
	ErrorCodeIncompatibleFeature   ErrorCode = "INCOMPATIBLE_FEATURE"
	ErrorCodeFieldMappingFailure   ErrorCode = "FIELD_MAPPING_FAILURE"
	ErrorCodeToolCallParseError    ErrorCode = "TOOL_CALL_PARSE_ERROR"
	ErrorCodeJSONParseError        ErrorCode = "JSON_PARSE_ERROR"
	ErrorCodeStreamStateError      ErrorCode = "STREAM_STATE_ERROR"
	ErrorCodeUTF8DecodeError       ErrorCode = "UTF8_DECODE_ERROR"
	ErrorCodeProtocolConstraint    ErrorCode = "PROTOCOL_CONSTRAINT_VIOLATION"
	ErrorCodeEncodingFailure       ErrorCode = "ENCODING_FAILURE"
	ErrorCodeInterfaceNotSupported ErrorCode = "INTERFACE_NOT_SUPPORTED"
	ErrorCodeUnsupportedMultimodal ErrorCode = "UNSUPPORTED_MULTIMODAL"
)

const (
	ErrorDetailPhase   = "phase"
	ErrorPhaseRequest  = "request"
	ErrorPhaseResponse = "response"
)

// ConversionError 协议转换错误
type ConversionError struct {
	Code             ErrorCode
	Message          string
	ClientProtocol   string
	ProviderProtocol string
	InterfaceType    string
	Details          map[string]any
	Cause            error
}

// NewConversionError 创建转换错误
func NewConversionError(code ErrorCode, message string) *ConversionError {
	return &ConversionError{
		Code:    code,
		Message: message,
		Details: make(map[string]any),
	}
}

// NewRequestJSONParseError 创建请求 JSON 解析错误。
func NewRequestJSONParseError(message string, cause error) *ConversionError {
	return NewConversionError(ErrorCodeJSONParseError, message).
		WithDetail(ErrorDetailPhase, ErrorPhaseRequest).
		WithCause(cause)
}

// NewResponseJSONParseError 创建响应 JSON 解析错误。
func NewResponseJSONParseError(message string, cause error) *ConversionError {
	return NewConversionError(ErrorCodeJSONParseError, message).
		WithDetail(ErrorDetailPhase, ErrorPhaseResponse).
		WithCause(cause)
}

// WithClientProtocol 设置客户端协议
func (e *ConversionError) WithClientProtocol(protocol string) *ConversionError {
	e.ClientProtocol = protocol
	return e
}

// WithProviderProtocol 设置服务端协议
func (e *ConversionError) WithProviderProtocol(protocol string) *ConversionError {
	e.ProviderProtocol = protocol
	return e
}

// WithInterfaceType 设置接口类型
func (e *ConversionError) WithInterfaceType(ifaceType string) *ConversionError {
	e.InterfaceType = ifaceType
	return e
}

// WithDetail 添加详情
func (e *ConversionError) WithDetail(key string, value any) *ConversionError {
	e.Details[key] = value
	return e
}

// WithCause 设置原因
func (e *ConversionError) WithCause(cause error) *ConversionError {
	e.Cause = cause
	return e
}

// Error 实现 error 接口
func (e *ConversionError) Error() string {
	if e.Cause != nil {
		return fmt.Sprintf("[%s] %s: %v", e.Code, e.Message, e.Cause)
	}
	return fmt.Sprintf("[%s] %s", e.Code, e.Message)
}

// Unwrap 支持 errors.Is/As
func (e *ConversionError) Unwrap() error {
	return e.Cause
}
