package com.petshop.backend.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.petshop.backend.dto.ai.AiChatRequest;
import com.petshop.backend.entity.Pet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;

@Service
public class OpenRouterService {

    private static final String OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";

    @Value("${openrouter.api-key:}")
    private String apiKey;

    @Value("${openrouter.model:meta-llama/llama-3.3-70b-instruct:free}")
    private String model;

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();

    public String chat(List<AiChatRequest.ChatHistoryItem> history, String userMessage, List<Pet> userPets) {
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalStateException("OpenRouter API key is not configured");
        }

        try {
            String systemPrompt = buildSystemPrompt(userPets);
            String requestBody = buildRequestBody(systemPrompt, history, userMessage);

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(OPENROUTER_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .timeout(Duration.ofSeconds(60))
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() != 200) {
                throw new RuntimeException("OpenRouter API returned status " + response.statusCode() + ": " + response.body());
            }

            return extractContent(response.body());
        } 
        
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("AI request was interrupted", e);
        }
        catch (Exception e) {
            throw new RuntimeException("Failed to call OpenRouter API: " + e.getMessage(), e);
        }
    }

    private String buildSystemPrompt(List<Pet> userPets) {
        StringBuilder sb = new StringBuilder();
        sb.append("You are a helpful AI assistant for Leon's Pet Store, specializing in pet ownership and adoption advice. ");
        sb.append("You help customers with pet care requirements, supplies (food, habitat, grooming, etc.), ");
        sb.append("veterinary and grooming appointments, and general pet-related questions. ");
        sb.append("You can recommend pets based on the user's experience level (beginner, intermediate, expert). ");
        sb.append("Always be friendly, informative, and focused on pet-related topics.\n\n");

        if (userPets != null && !userPets.isEmpty()) {
            sb.append("The user currently owns the following pets:\n");
            for (Pet pet : userPets) {
                sb.append("- ").append(pet.getPetName());
                sb.append(" (").append(pet.getPetSpecies());

                if (pet.getPetBreed() != null && !pet.getPetBreed().isBlank()) {
                    sb.append(", ").append(pet.getPetBreed());
                }

                if (pet.getPetAge() != null) {
                    sb.append(", ").append(pet.getPetAge()).append(" year(s) old");
                }
                sb.append(")\n");
            }
            sb.append("Use this information to personalize your responses when relevant.\n");
        } 
        
        else {
            sb.append("The user does not currently own any pets registered in the system.\n");
        }

        return sb.toString();
    }

    private String buildRequestBody(String systemPrompt, List<AiChatRequest.ChatHistoryItem> history, String userMessage) throws Exception {
        ObjectNode root = objectMapper.createObjectNode();
        root.put("model", model);

        ArrayNode messages = root.putArray("messages");

        ObjectNode systemMsg = messages.addObject();
        systemMsg.put("role", "system");
        systemMsg.put("content", systemPrompt);

        if (history != null) {
            for (AiChatRequest.ChatHistoryItem item : history) {
                ObjectNode msg = messages.addObject();
                msg.put("role", item.getRole());
                msg.put("content", item.getContent());
            }
        }

        ObjectNode userMsg = messages.addObject();
        userMsg.put("role", "user");
        userMsg.put("content", userMessage);

        return objectMapper.writeValueAsString(root);
    }

    private String extractContent(String responseBody) throws Exception {
        JsonNode root = objectMapper.readTree(responseBody);
        JsonNode choices = root.path("choices");
        if (choices.isArray() && choices.size() > 0) {
            return choices.get(0).path("message").path("content").asText();
        }
        
        throw new RuntimeException("No content in OpenRouter response: " + responseBody);
    }
}
