package services

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

type OpenAIService struct {
    apiKey string
}

type OpenAIRequest struct {
    Model       string    `json:"model"`
    Messages    []Message `json:"messages"`
    Temperature float64   `json:"temperature"`
}

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type OpenAIResponse struct {
    Choices []struct {
        Message struct {
            Content string `json:"content"`
        } `json:"message"`
    } `json:"choices"`
}

func NewOpenAIService(apiKey string) *OpenAIService {
    return &OpenAIService{apiKey: apiKey}
}

func (s *OpenAIService) GenerateDIY(query string) (string, error) {
    url := "https://api.openai.com/v1/chat/completions"
    
    prompt := fmt.Sprintf("Generate creative DIY project ideas to repurpose or recycle the following: %s. Provide detailed instructions, materials needed, and steps to create each project.", query)
    
    requestBody := OpenAIRequest{
        Model: "gpt-4", // or "gpt-3.5-turbo" depending on your needs/access
        Messages: []Message{
            {
                Role:    "system",
                Content: "You are a creative DIY expert who helps people repurpose and recycle items into useful projects.",
            },
            {
                Role:    "user",
                Content: prompt,
            },
        },
        Temperature: 0.7,
    }
    
    jsonData, err := json.Marshal(requestBody)
    if err != nil {
        return "", err
    }
    
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return "", err
    }
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", s.apiKey))
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    
    var response OpenAIResponse
    if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
        return "", err
    }
    
    if len(response.Choices) == 0 {
        return "", fmt.Errorf("no response from OpenAI")
    }
    
    return response.Choices[0].Message.Content, nil
}