package adk

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

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

// SupersedeTool provides error correction with cascade tracking.
//
// Used by Human Supervisor to correct bad assertions.
type SupersedeTool struct {
	client EpistemeClient
}

// NewSupersedeTool creates a new Supersede tool.
func NewSupersedeTool(client EpistemeClient) *SupersedeTool {
	return &SupersedeTool{client: client}
}

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

// Description returns the tool description.
func (t *SupersedeTool) Description() string {
	return "Supersede a bad assertion with correction tracking. " +
		"Shows cascade impact on downstream assertions. " +
		"Used for incident remediation and knowledge correction."
}

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

	// Convert SupersessionType
	superType := parseSupersessionType(params.Type)

	// Build SupersedeParams
	supersedeParams := steme.SupersedeParams{
		TargetHash:       params.Hash,
		SupersessionType: superType,
		Reason:           params.Reason,
		NewHash:          params.NewHash,
		AgentID:          params.AgentID,
		Signature:        params.Signature,
	}

	// Execute supersede
	result, err := t.client.Supersede(ctx, supersedeParams)
	if err != nil {
		return nil, fmt.Errorf("supersede failed: %w", err)
	}

	// Convert to SupersedeOutput format
	output := SupersedeOutput{
		Success:          true,
		TargetHash:       result.TargetHash,
		SupersessionType: string(result.SupersessionType),
		Timestamp:        result.Timestamp,
	}

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