package controllers

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/gofiber/fiber/v2"
)

type DataIa struct {
	Prompt string `json:"prompt"`
	Model  string `json:"model"`
	Stream bool `json:"stream"`
}

type respuestaOllama struct {
	Response string `json:"response"`
	Done     bool   `json:"done"`
}

func GeneraTextoStream(c *fiber.Ctx) error {
    var data DataIa
    if err := c.BodyParser(&data); err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
    }

    // Forzar stream = true
    data.Stream = true

    jsonData, err := json.Marshal(data)
    if err != nil {
        return err
    }

    req, err := http.NewRequest("POST", "https://n8n.u-s.app/webhook/c945b974-f534-419b-a6da-4ebd832f8cd9", bytes.NewBuffer(jsonData))
    if err != nil {
        return err
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer sk-43804e00f5294200ad1e599550fbee4f")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }

    // Configurar headers para streaming
    c.Set("Content-Type", "text/plain; charset=utf-8")
    c.Set("Cache-Control", "no-cache")
    c.Set("Connection", "keep-alive")

    c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
        defer resp.Body.Close()

        scanner := bufio.NewScanner(resp.Body)

        for scanner.Scan() {
            line := scanner.Bytes()
            if len(line) == 0 {
                continue
            }

            var msg respuestaOllama
            if err := json.Unmarshal(line, &msg); err != nil {
                continue
            }

            if msg.Response != "" {
                fmt.Fprint(w, msg.Response)
                w.Flush() // <-- envía inmediatamente
            }

            if msg.Done {
                break
            }
        }
    })

    return nil
}

