package com.bytesw.bytebot.service;

import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.bytebot.http.FileValidationResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Log4j2
public class KnowledgeService {

    @Value("${application.bucket.tenant}")
    private String tenant;

    @Value("${application.knowledge.url}")
    private String url;

    @Value("${application.bucket.version}")
    private String version;

    public boolean generate(FileValidationResponse response) throws IOException {
        boolean result = false;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(String.format("%s/clients/%s/versions/%s", url, tenant, version));
        String json = String.format("{\"filename_csv\": \"%s\", \"index_name\": \"%s\"}",response.getFileName(), response.getUuid());
        StringEntity entity = new StringEntity(json);
        try {
            httppost.setEntity(entity);
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-type", "application/json");
            ResponseHandler<String> responseHandler = resp -> {
                int status = resp.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entityRes = resp.getEntity();
                    return entityRes != null ? EntityUtils.toString(entityRes) : null;
                } else {
                    throw new ClientProtocolException("Error inesperado: " + status);
                }
            };
            String res = httpclient.execute(httppost, responseHandler);
            String status = (String) JsonUtils.getFieldFromJson(res, "$.message.status");
            httpclient.close();
            if (status.equals("success")){
                result = true;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return result;
    }

    public boolean delete(String uuid) {
        boolean result = false;
        try {
            HttpDelete httpDelete = new HttpDelete(String.format("%s/clients/%s/indexes/%s/versions/%s", url, tenant, uuid, version));
            ResponseHandler<String> responseHandler = response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Error inesperado: " + status);
                }
            };
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String res = httpclient.execute(httpDelete, responseHandler);
            httpclient.close();
            String status = (String) JsonUtils.getFieldFromJson(res, "$.message.status");
            if (status.equals("success")){
                result = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
