package pgxtraces

import (
	
	
	
	

	
	
	

	
)

const scopeName = "go.pact.im/x/traces/pgxtraces"

const (
	attrDBSystemName         = "db.system.name"
	attrDBNamespace          = "db.namespace"
	attrDBOperationName      = "db.operation.name"
	attrDBQueryText          = "db.query.text"
	attrDBCollectionName     = "db.collection.name"
	attrDBBatchSize          = "db.operation.batch.size"
	attrDBReturnedRows       = "db.response.returned_rows"
	attrDBResponseStatusCode = "db.response.status_code"
	attrServerAddress        = "server.address"
	attrServerPort           = "server.port"
	attrErrorType            = "error.type"
	dbSystemPostgreSQL       = "postgresql"
)

const (
	opBatch   = "BATCH"
	opCopy    = "COPY"
	opPrepare = "PREPARE"
	opConnect = "CONNECT"
	opAcquire = "ACQUIRE"
)

// Tracer traces pgx v5 operations using [traces.Tracer]. It implements
// [pgx.QueryTracer], [pgx.BatchTracer], [pgx.CopyFromTracer],
// [pgx.PrepareTracer], [pgx.ConnectTracer], and [pgxpool.AcquireTracer].
//
// Assign a Tracer to [pgx.ConnConfig.Tracer] (or pgxpool.Config.ConnConfig.Tracer).
// Query arguments are never recorded; SQL text is recorded in db.query.text by
// default and can be redacted or omitted via [Tracer.WithQueryText].
// [pgx.ErrNoRows] is not marked as a span error.
type Tracer struct {
	tracer    *traces.Tracer
	filter    func(ctx context.Context, op string) bool
	queryText func(sql string) (string, bool)
	spanName  func(op, db string) string
	attrs     func(ctx context.Context) []traces.Attr
}

var (
	_ pgx.QueryTracer       = (*Tracer)(nil)
	_ pgx.BatchTracer       = (*Tracer)(nil)
	_ pgx.CopyFromTracer    = (*Tracer)(nil)
	_ pgx.PrepareTracer     = (*Tracer)(nil)
	_ pgx.ConnectTracer     = (*Tracer)(nil)
	_ pgxpool.AcquireTracer = (*Tracer)(nil)
)

// New returns a new [Tracer] instance using tr.
func ( *traces.Tracer) *Tracer {
	return &Tracer{
		tracer:    .WithScope(scopeName),
		queryText: defaultQueryText,
		spanName:  defaultSpanName,
	}
}

// WithFilter returns a [Tracer] that only traces operations for which f returns
// true. The op argument is the uppercased SQL verb (such as "SELECT") or one of
// "BATCH", "COPY", "PREPARE", "CONNECT", or "ACQUIRE". If f is nil, all
// operations are traced.
func ( *Tracer) ( func( context.Context,  string) bool) *Tracer {
	 := *
	.filter = 
	return &
}

// WithQueryText returns a [Tracer] using f to transform or filter SQL text
// before recording it in db.query.text. Returning ok == false omits
// db.query.text. If f is nil, it restores recording the SQL string as-is.
func ( *Tracer) ( func( string) ( string,  bool)) *Tracer {
	if  == nil {
		 = defaultQueryText
	}
	 := *
	.queryText = 
	return &
}

// WithSpanName returns a [Tracer] using f to compute the span name from the
// operation and database namespace. If f is nil, it restores the default
// "{op} {db}" naming.
func ( *Tracer) ( func(,  string) string) *Tracer {
	if  == nil {
		 = defaultSpanName
	}
	 := *
	.spanName = 
	return &
}

// WithAttrs returns a [Tracer] using f to attach additional start-time
// attributes for each operation. If f is nil, only default attributes are
// added.
func ( *Tracer) ( func( context.Context) []traces.Attr) *Tracer {
	 := *
	.attrs = 
	return &
}

func ( *Tracer) (
	 context.Context,
	 *pgx.ConnConfig,
	 string,
) []traces.Attr {
	 := []traces.Attr{
		traces.String(attrDBSystemName, dbSystemPostgreSQL),
	}
	if  != "" {
		 = append(, traces.String(attrDBOperationName, ))
	}
	if  != nil {
		if .Database != "" {
			 = append(, traces.String(attrDBNamespace, .Database))
		}
		if .Host != "" {
			 = append(, traces.String(attrServerAddress, .Host))
		}
		if .Port != 0 {
			 = append(, traces.Int(attrServerPort, int(.Port)))
		}
	}
	if .attrs != nil {
		 = append(, .attrs()...)
	}
	return 
}

func ( string) (string, bool) {
	if  == "" {
		return "", false
	}
	return , true
}

func (,  string) string {
	switch {
	case  != "" &&  != "":
		return  + " " + 
	case  != "":
		return 
	case  != "":
		return 
	default:
		return dbSystemPostgreSQL
	}
}

func ( *pgx.ConnConfig) string {
	if  == nil {
		return ""
	}
	return .Database
}

func ( *Tracer) ( context.Context,  string) bool {
	return .filter == nil || .filter(, )
}

func ( *traces.Span,  error) {
	if  == nil || errors.Is(, pgx.ErrNoRows) {
		return
	}
	if ,  := errors.AsType[*pgconn.PgError]();  && .Code != "" {
		.SetAttrs(
			traces.String(attrDBResponseStatusCode, .Code),
			traces.String(attrErrorType, .Code),
		)
	} else {
		.SetAttrs(traces.String(attrErrorType, fmt.Sprintf("%T", )))
	}
	.SetError()
}

func ( string) string {
	 = skipSQLComments()
	if  := strings.IndexAny(, " \t\n\r(");  > 0 {
		 = [:]
	}
	return strings.ToUpper()
}

// sqlCollection extracts the target table name for common single-target SQL
// statements (SELECT/DELETE ... FROM <table>, INSERT INTO <table>,
// UPDATE <table>, TRUNCATE [TABLE] <table>). It returns "" for subqueries,
// CTEs, or unrecognized syntax.
func (,  string) string {
	 := skipSQLComments()
	if  == "" {
		return ""
	}
	var  string
	switch  {
	case "SELECT", "DELETE":
		 = afterSQLKeyword(, "FROM")
	case "INSERT":
		 = afterSQLKeyword(, "INTO")
	case "UPDATE":
		_,  = nextSQLToken()
	case "TRUNCATE":
		_,  = nextSQLToken()
		if ,  := nextSQLToken(); strings.EqualFold(, "TABLE") {
			 = 
		}
	default:
		return ""
	}
	if  == "" {
		return ""
	}
	,  := nextSQLToken()
	if strings.EqualFold(, "ONLY") {
		, _ = nextSQLToken()
	}
	if  == "" || strings.HasPrefix(, "(") {
		return ""
	}
	return strings.TrimRight(, ",;(")
}

func (,  string) string {
	for  != "" {
		,  := nextSQLToken()
		if  == "" {
			return ""
		}
		if strings.EqualFold(, ) {
			return 
		}
		 = 
	}
	return ""
}

func ( string) (,  string) {
	 = skipSQLComments()
	if  == "" {
		return "", ""
	}
	 := 0
	 := false
	for  < len() {
		 := []
		if  == '"' {
			 = !
			++
			continue
		}
		if ! && ( == ' ' ||  == '\t' ||  == '\n' ||  == '\r') {
			break
		}
		++
	}
	return [:], [:]
}

func ( string) string {
	for {
		 = strings.TrimSpace()
		switch {
		case strings.HasPrefix(, "--"):
			, ,  := strings.Cut(, "\n")
			if ! {
				return ""
			}
			 = 
		case strings.HasPrefix(, "/*"):
			 := 1
			 := 2
			for  < len() &&  > 0 {
				if +1 < len() && [] == '/' && [+1] == '*' {
					++
					 += 2
					continue
				}
				if +1 < len() && [] == '*' && [+1] == '/' {
					--
					 += 2
					continue
				}
				++
			}
			if  > 0 {
				return ""
			}
			 = [:]
		default:
			return 
		}
	}
}