package com.saas.voip.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Service for interacting with Telnyx Voice AI
 * Alternative to Twilio + OpenAI Realtime API
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TelnyxVoiceAIService {

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${telnyx.api.key:}")
    private String telnyxApiKey;

    @Value("${telnyx.voice.ai.assistant.id:}")
    private String defaultAIAssistantId;

    private static final String TELNYX_API_BASE = "https://api.telnyx.com/v2";

    /**
     * Start Telnyx Voice AI on an active call
     */
    public void startVoiceAI(String callControlId, String aiAssistantId) {
        try {
            String url = TELNYX_API_BASE + "/calls/" + callControlId + "/actions/start_ai_assistant";

            Map<String, Object> payload = new HashMap<>();
            payload.put("ai_assistant_id", aiAssistantId != null ? aiAssistantId : defaultAIAssistantId);
            payload.put("client_state", encodeMetadata(callControlId));

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

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(payload, headers);

            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, request, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("✅ Telnyx Voice AI started on call: {}", callControlId);
            } else {
                log.error("❌ Failed to start Voice AI. Status: {}", response.getStatusCode());
            }

        } catch (Exception e) {
            log.error("Error starting Telnyx Voice AI on call: {}", callControlId, e);
        }
    }

    /**
     * Stop Telnyx Voice AI on an active call
     */
    public void stopVoiceAI(String callControlId) {
        try {
            String url = TELNYX_API_BASE + "/calls/" + callControlId + "/actions/stop_ai_assistant";

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

            HttpEntity<Void> request = new HttpEntity<>(headers);

            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, request, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("🛑 Telnyx Voice AI stopped on call: {}", callControlId);
            }

        } catch (Exception e) {
            log.error("Error stopping Telnyx Voice AI on call: {}", callControlId, e);
        }
    }

    /**
     * Retrieve conversation transcript from Telnyx
     */
    public Map<String, Object> getConversationTranscript(String callSessionId) {
        try {
            String url = TELNYX_API_BASE + "/ai/conversations/" + callSessionId;

            HttpHeaders headers = new HttpHeaders();
            headers.setBearerAuth(telnyxApiKey);

            HttpEntity<Void> request = new HttpEntity<>(headers);

            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, request, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("📄 Retrieved conversation transcript for: {}", callSessionId);
                return response.getBody();
            }

        } catch (Exception e) {
            log.error("Error retrieving conversation transcript: {}", callSessionId, e);
        }

        return Map.of();
    }

    /**
     * Configure AI assistant instructions dynamically (if supported)
     */
    public void updateAIInstructions(String aiAssistantId, String instructions) {
        try {
            String url = TELNYX_API_BASE + "/ai/assistants/" + aiAssistantId;

            Map<String, Object> payload = new HashMap<>();
            payload.put("instructions", instructions);

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

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(payload, headers);

            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.PATCH, request, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("✅ Updated AI assistant instructions: {}", aiAssistantId);
            }

        } catch (Exception e) {
            log.error("Error updating AI instructions for: {}", aiAssistantId, e);
        }
    }

    /**
     * Encode metadata for client_state parameter
     */
    private String encodeMetadata(String callControlId) {
        try {
            Map<String, String> metadata = new HashMap<>();
            metadata.put("call_control_id", callControlId);
            metadata.put("timestamp", String.valueOf(System.currentTimeMillis()));
            return objectMapper.writeValueAsString(metadata);
        } catch (Exception e) {
            log.error("Error encoding metadata", e);
            return "{}";
        }
    }
}
