package adk

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

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

// TraceTool provides audit trail queries for incident investigation.
//
// Used by On-Call SRE and Human Supervisor to trace agent decisions.
type TraceTool struct {
	client EpistemeClient
}

// NewTraceTool creates a new Trace tool.
func NewTraceTool(client EpistemeClient) *TraceTool {
	return &TraceTool{client: client}
}

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

// Description returns the tool description.
func (t *TraceTool) Description() string {
	return "Trace agent queries for incident investigation. " +
		"Shows what an agent queried, when, and what values were returned. " +
		"CRITICAL for debugging production incidents."
}

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

	// Build StemeDB trace params
	traceParams := steme.TraceParams{
		AgentID: params.AgentID,
		From:    params.From,
		To:      params.To,
		Subject: params.Subject,
		Limit:   100, // Default limit
	}

	// Execute trace
	result, err := t.client.Trace(ctx, traceParams)
	if err != nil {
		return nil, fmt.Errorf("trace query failed: %w", err)
	}

	// Convert to TraceOutput format
	output := convertTraceResult(result)

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