package adk

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

	"github.com/orchard9/stemedb-go/steme"
)

// QueryTool provides lens-based knowledge retrieval.
//
// Used by all agents to retrieve current knowledge with conflict resolution.
type QueryTool struct {
	client EpistemeClient
}

// NewQueryTool creates a new Query tool.
func NewQueryTool(client EpistemeClient) *QueryTool {
	return &QueryTool{client: client}
}

// Name returns the tool name.
func (t *QueryTool) Name() string {
	return "episteme_query"
}

// Description returns the tool description.
func (t *QueryTool) Description() string {
	return "Query Episteme knowledge graph with lens-based conflict resolution. " +
		"Returns resolved value with confidence score and source provenance. " +
		"CRITICAL: Always filter by lifecycle=approved for production decisions."
}

// Execute performs the query operation.
func (t *QueryTool) Execute(ctx context.Context, input []byte) ([]byte, error) {
	var params QueryInput
	if err := json.Unmarshal(input, &params); err != nil {
		return nil, fmt.Errorf("invalid query input: %w", err)
	}

	// Build StemeDB query params
	builder := steme.NewQuery()

	if params.Subject != "" {
		builder.WithSubject(params.Subject)
	}

	if params.Predicate != "" {
		builder.WithPredicate(params.Predicate)
	}

	if params.Lens != "" {
		lens := parseLen(params.Lens)
		builder.WithLens(lens)
	}

	if params.Lifecycle != "" {
		lifecycle := parseLifecycle(params.Lifecycle)
		builder.WithLifecycle(lifecycle)
	}

	// Execute query
	result, err := t.client.Query(ctx, builder.Build())
	if err != nil {
		errorOutput, marshalErr := json.Marshal(QueryOutput{
			Error: err.Error(),
		})
		if marshalErr != nil {
			return nil, fmt.Errorf("query failed: %w", err)
		}
		return errorOutput, nil
	}

	// Convert to QueryOutput format
	output := convertQueryResult(result, params.MinConfidence)

	outputBytes, err := json.Marshal(output)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal query output: %w", err)
	}
	return outputBytes, nil
}
