package llm

import (
	"context"
	"fmt"
	"os"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

// Client handles communication with the Anthropic API
type Client struct {
	client *anthropic.Client
}

// NewClient creates a new Anthropic API client
func NewClient() (*Client, error) {
	apiKey := os.Getenv("ANTHROPIC_API_KEY")
	if apiKey == "" {
		return nil, fmt.Errorf("ANTHROPIC_API_KEY environment variable not set. Please set it to use LLM-based policy extraction")
	}

	client := anthropic.NewClient(
		option.WithAPIKey(apiKey),
	)

	return &Client{
		client: &client,
	}, nil
}

// SendMessage sends a message to Claude and returns the response
func (c *Client) SendMessage(ctx context.Context, prompt string) (string, error) {
	message, err := c.client.Messages.New(ctx, anthropic.MessageNewParams{
		MaxTokens: 8192,
		Messages: []anthropic.MessageParam{
			anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
		},
		Model: anthropic.ModelClaudeHaiku4_5_20251001,
	})
	if err != nil {
		return "", fmt.Errorf("failed to send message: %w", err)
	}

	// Extract text from content blocks
	if len(message.Content) == 0 {
		return "", fmt.Errorf("empty response from API")
	}

	// Get text from all content blocks and concatenate
	var result string
	for _, block := range message.Content {
		if block.Text != "" {
			result += block.Text
		}
	}

	if result == "" {
		return "", fmt.Errorf("no text content in response")
	}

	return result, nil
}
