<?php

namespace Mtc\Plugins\Agent\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Event;
use Mtc\Plugins\Agent\Agents\PharmacyAgent;
use Mtc\Plugins\Agent\Events\ChatGenerated;
use NeuronAI\Chat\Messages\UserMessage;
use OpenAI;

class ChatController extends Controller
{
    protected string $openai_api_key;

    public function __construct()
    {
        $this->openai_api_key = config('neuron.openai.key');
    }


    public function sendMessage(Request $request)
    {
        $request->validate([
            'message' => 'required|string',
        ]);

        $agent = PharmacyAgent::make();
        $message = $request->input('message');

        $productOutput = $this->AgentCommunicate($message);
        // 👆 This returns an instance of ProductOutput, not a string.

        // Now you can access the properties of the ProductOutput object
        $productName = $productOutput->name;
        $chatResponse = $productOutput->response;
        $productId = $productOutput->productId;

        $item = new \Item();
        $item->Get_Item($productId);

        ChatGenerated::dispatch($chatResponse, $productName, $productId, $item);

        return response()->json(['status' => 'message sent']);
    }
    private function AgentCommunicate($message)
    {
        $agent = PharmacyAgent::make();
        $userMessage = new UserMessage($message);

        $response = $agent->structured($userMessage);

        return $response;
    }
    /**
     * @description Audio whisper
     * */
    public function audioWhisper(Request $request) {
        $request->validate([
            'audio_file' => 'required|file|mimes:mp3,wav,aac,mp4,webm',
        ]);

        $filename = 'whisper_upload_' . uniqid() . '.webm';

        $audioFile = $request->file('audio_file');
        $path = $audioFile->storeAs('temp_whisper', $filename);
        $fullPath = storage_path('app/' . $path);

        try {
            $client = OpenAI::client($this->openai_api_key);
            $response = $client->audio()->transcribe([
                'model' => 'whisper-1',
                'file' => fopen($fullPath, 'r'),
                'response_format' => 'verbose_json',
                'timestamp_granularities' => ['segment', 'word']
            ]);
            return response()->json($response);

        } catch (\Exception $e) {
            return response()->json(['error' => 'Transcription failed: ' . $e->getMessage()], 500);
        } finally {
            // Clean up the uploaded file
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
        }
    }


    public function audioTTS(Request $request)
    {
        $headers = [
            'Content-Type'        => 'audio/mpeg', // Matches 'tts-1' default output
            'Content-Disposition' => 'inline; filename="speech.mp3"', // 'inline' allows browser playback
            'Cache-Control'       => 'no-cache',
            'X-Accel-Buffering'   => 'no', // Important for Nginx to disable buffering
        ];
        $client = OpenAI::client($this->openai_api_key);
        return response()->stream(function () use ($client , $request) {

            // Request the stream from OpenAI

            $stream = $client->audio()->speechStreamed([
                'model' => 'tts-1',
                'input' => $request->input('text'),
                'voice' => 'alloy',
            ]);

            // Iterate and Output
            foreach ($stream as $chunk) {
                echo $chunk;

                // Force PHP to send the buffer to the browser immediately
                if (ob_get_level() > 0) {
                    ob_flush();
                }
                flush();
            }

        }, 200, $headers);

    }

}
