package com.avitam.bankloanapplication.service;

import com.avitam.bankloanapplication.enumCategory.LoanCategory;
import com.avitam.bankloanapplication.model.AIDto.AIRequest;
import com.avitam.bankloanapplication.model.AIDto.AIResponse;
import com.avitam.bankloanapplication.model.AIDto.PromptRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Locale;

@Service
public class ChatAIService {

    private final RestTemplate restTemplate;
    @Value("${openapi.api.key}")
    private String apiKey;
    @Value("${openapi.api.model}")
    private String model;
    @Value("${openapi.api.url}") // Example: https://api.openai.com/v1/chat/completions
    private String apiUrl;

    public ChatAIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getChatResponse(PromptRequest promptRequest) {
        String userPrompt = promptRequest.prompt();
        LoanCategory category = detectCategory(userPrompt);

        if (category == LoanCategory.OTHER) {
            return "Sorry, I can only answer questions related to loans and banking. Please ask a relevant question.";
        }

        String systemPrompt = switch (category) {
            case HOME_LOAN -> "You are a banking assistant specializing in home loans.";
            case PERSONAL_LOAN -> "You are a banking assistant specializing in personal loans.";
            case EDUCATION_LOAN -> "You are a banking assistant focusing on education loans.";
            case LOAN_ELIGIBILITY -> "You assist users in understanding loan eligibility criteria.";
            case INTEREST_RATE -> "You provide current interest rates for various banking services.";
            case DOCUMENTATION -> "You help users with required documents for banking services.";
            case CREDIT_CARD -> "You are a banking assistant providing information about credit cards.";
            case SAVINGS_ACCOUNT -> "You guide users about savings account features and benefits.";
            case CURRENT_ACCOUNT -> "You help users with business/current account-related queries.";
            case INSURANCE -> "You assist users with insurance plans, policies, and premiums.";
            case FIXED_DEPOSIT -> "You explain fixed deposit (FD) schemes and interest options.";
            case GENERAL_BANKING ->
                    "You answer general banking queries like branch hours, ATM issues, net banking, etc.";
            default -> throw new IllegalStateException("Unexpected value: " + category);
        } + " If the user asks something outside this scope, respond with: 'Please ask a question related to "
                + category.name().toLowerCase().replace("_", " ") + " only.'";
        AIRequest aiRequest = new AIRequest(
                model,
                List.of(
                        new AIRequest.Message("system", systemPrompt),
                        new AIRequest.Message("user", userPrompt)
                )
        );

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        HttpEntity<AIRequest> requestEntity = new HttpEntity<>(aiRequest, headers);

        ResponseEntity<AIResponse> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                requestEntity,
                AIResponse.class
        );

        if (response.getBody() != null &&
                response.getBody().choices() != null &&
                !response.getBody().choices().isEmpty()) {
            return response.getBody().choices().get(0).message().content();
        } else {
            return "No valid response received from the AI.";
        }
    }


    private LoanCategory detectCategory(String prompt) {
        String lowerPrompt = prompt.toLowerCase(Locale.ROOT);

        if (lowerPrompt.contains("home loan") || lowerPrompt.contains("housing loan")) {
            return LoanCategory.HOME_LOAN;
        } else if (lowerPrompt.contains("personal loan") || lowerPrompt.contains("instant loan")) {
            return LoanCategory.PERSONAL_LOAN;
        } else if (lowerPrompt.contains("education loan") || lowerPrompt.contains("student loan")) {
            return LoanCategory.EDUCATION_LOAN;
        } else if (lowerPrompt.contains("eligible") || lowerPrompt.contains("eligibility") || lowerPrompt.contains("requirements")) {
            return LoanCategory.LOAN_ELIGIBILITY;
        } else if (lowerPrompt.contains("interest") || lowerPrompt.contains("rate")) {
            return LoanCategory.INTEREST_RATE;
        } else if (lowerPrompt.contains("document") || lowerPrompt.contains("proof") || lowerPrompt.contains("kyc")) {
            return LoanCategory.DOCUMENTATION;
        } else if (lowerPrompt.contains("credit card") || lowerPrompt.contains("card limit") || lowerPrompt.contains("card issue")) {
            return LoanCategory.CREDIT_CARD;
        } else if (lowerPrompt.contains("savings account") || lowerPrompt.contains("save money")) {
            return LoanCategory.SAVINGS_ACCOUNT;
        } else if (lowerPrompt.contains("current account") || lowerPrompt.contains("business account")) {
            return LoanCategory.CURRENT_ACCOUNT;
        } else if (lowerPrompt.contains("insurance") || lowerPrompt.contains("policy") || lowerPrompt.contains("premium")) {
            return LoanCategory.INSURANCE;
        } else if (lowerPrompt.contains("fixed deposit") || lowerPrompt.contains("fd") || lowerPrompt.contains("term deposit")) {
            return LoanCategory.FIXED_DEPOSIT;
        } else if (lowerPrompt.contains("bank") || lowerPrompt.contains("branch") || lowerPrompt.contains("atm") || lowerPrompt.contains("net banking")) {
            return LoanCategory.GENERAL_BANKING;
        } else {
            return LoanCategory.OTHER;
        }
    }

}



