package com.saas.voip.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * Gemini Realtime Controller
 * 
 * Provides TwiML endpoints for Twilio to connect calls to Gemini 2.0 Flash Live API
 * 
 * Flow:
 * 1. Twilio receives inbound call
 * 2. Twilio webhook calls /api/voip/gemini/twiml
 * 3. Returns TwiML with <Stream> pointing to WebSocket endpoint
 * 4. Twilio establishes WebSocket to /api/voip/gemini/stream
 * 5. GeminiSessionHandler manages bidirectional streaming
 * 
 * Cost Savings vs OpenAI:
 * - Gemini: ~$0.010 USD per 2-minute call
 * - OpenAI: ~$0.165 USD per 2-minute call
 * - 16x cheaper! 🎉
 */
@RestController
@RequestMapping("/api/voip/gemini")
@RequiredArgsConstructor
@Slf4j
public class GeminiRealtimeController {

    @Value("${server.base-url:http://localhost:8000}")
    private String serverBaseUrl;

    /**
     * TwiML endpoint for Gemini voice calls
     * 
     * Twilio calls this endpoint when a call is received
     * Returns TwiML that connects Twilio's Media Streams to our WebSocket
     * 
     * @param To Destination phone number
     * @param From Caller phone number
     * @param CallSid Twilio call identifier
     * @return TwiML XML
     */
    @PostMapping(value = "/twiml", produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<String> handleIncomingCall(
            @RequestParam(required = false) String To,
            @RequestParam(required = false) String From,
            @RequestParam(required = false) String CallSid) {

        log.info("📞 [Gemini] Incoming call - From: {}, To: {}, CallSid: {}", From, To, CallSid);

        // Build WebSocket URL for Twilio Media Streams
        String wsUrl = serverBaseUrl
                .replace("http://", "wss://")
                .replace("https://", "wss://");
        wsUrl += "/api/voip/gemini/stream";

        // Build TwiML response
        String twiml = String.format("""
            <?xml version="1.0" encoding="UTF-8"?>
            <Response>
                <Say language="fr-FR">
                    Connexion à l'assistant Gemini. Veuillez patienter.
                </Say>
                <Connect>
                    <Stream url="%s">
                        <Parameter name="To" value="%s"/>
                        <Parameter name="From" value="%s"/>
                    </Stream>
                </Connect>
            </Response>
            """, wsUrl, To != null ? To : "", From != null ? From : "");

        log.info("✅ [Gemini] TwiML generated - WebSocket URL: {}", wsUrl);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_XML)
                .body(twiml);
    }

    /**
     * Health check endpoint
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("Gemini Realtime API integration is running!");
    }

    /**
     * Status endpoint with pricing info
     */
    @GetMapping("/status")
    public ResponseEntity<Object> status() {
        return ResponseEntity.ok(new Object() {
            public final String provider = "Gemini 2.0 Flash";
            public final String model = "gemini-2.0-flash-exp";
            public final String status = "Active";
            public final Object pricing = new Object() {
                public final String audioInputTokens = "$0.30 per 1M tokens";
                public final String audioOutputTokens = "$1.20 per 1M tokens";
                public final String estimatedCostPer2MinCall = "$0.010 USD";
                public final String savingsVsOpenAI = "16x cheaper! 🎉";
            };
            public final String[] supportedVoices = {
                "Aoede (Female, warm)",
                "Charon (Male, authoritative)", 
                "Fenrir (Male, bold)",
                "Kore (Female, soft)",
                "Puck (Male, friendly)"
            };
            public final String websocketEndpoint = "/api/voip/gemini/stream";
            public final String twimlEndpoint = "/api/voip/gemini/twiml";
        });
    }
}
