// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package customermedia

import (
	"bytes"
	"context"
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"wa-assistant/backend/processutil"
)

const MaxAVBytes = 16 << 20
const maxAudioSeconds = 180
const maxVideoSeconds = 120
const allowedFormats = "wav,ogg,mov,mp3,aac,flac,amr,matroska,webm"

var avSlots = make(chan struct{}, 1)

type Frame struct {
	At   float64
	Data []byte
}
type Video struct {
	Frames     []Frame
	Transcript string
	Duration   float64
	Note       string
}

type probeResult struct {
	Streams []struct {
		CodecType string `json:"codec_type"`
		Width     int    `json:"width"`
		Height    int    `json:"height"`
	} `json:"streams"`
	Format struct {
		Duration string `json:"duration"`
	} `json:"format"`
}

func acquireAV(ctx context.Context) error {
	select {
	case avSlots <- struct{}{}:
		return nil
	default:
		return errors.New("Pembaca suara/video sedang sibuk. Coba lagi sebentar.")
	}
}

func tempMedia(data []byte) (string, string, error) {
	if len(data) == 0 || len(data) > MaxAVBytes {
		return "", "", errors.New("Gunakan suara atau video berukuran maksimal 16 MB.")
	}
	dir, err := os.MkdirTemp("", "chatloop-customer-media-*")
	if err != nil {
		return "", "", errors.New("Penyimpanan sementara belum tersedia.")
	}
	path := filepath.Join(dir, "input.media")
	if os.WriteFile(path, data, 0o600) != nil {
		os.RemoveAll(dir)
		return "", "", errors.New("Media belum bisa dibuka.")
	}
	return dir, path, nil
}

func runMedia(ctx context.Context, name, env string, args ...string) ([]byte, error) {
	path := findBinary(name, env)
	if path == "" {
		return nil, errors.New("Pembaca media lokal belum tersedia.")
	}
	cmd := processutil.CommandContext(ctx, path, args...)
	var out cappedOutput
	out.max = 2 << 20
	cmd.Stdout = &out
	cmd.Stderr = io.Discard
	if err := cmd.Run(); err != nil {
		if ctx.Err() != nil {
			return nil, errors.New("Pembacaan media melewati batas waktu. Kirim klip yang lebih pendek.")
		}
		return nil, errors.New("Media rusak atau formatnya belum bisa dibaca. Coba kirim ulang.")
	}
	return out.Bytes(), nil
}

func probe(ctx context.Context, path string, maxSeconds float64) (probeResult, float64, error) {
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	out, err := runMedia(ctx, "ffprobe", "CHATLOOP_FFPROBE", "-v", "error", "-protocol_whitelist", "file,pipe", "-format_whitelist", allowedFormats, "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "json", path)
	if err != nil {
		return probeResult{}, 0, err
	}
	var p probeResult
	if json.Unmarshal(out, &p) != nil {
		return p, 0, errors.New("Durasi media belum dapat dibaca.")
	}
	duration, err := strconv.ParseFloat(p.Format.Duration, 64)
	if err != nil || math.IsNaN(duration) || math.IsInf(duration, 0) || duration <= 0 || duration > maxSeconds {
		return p, 0, fmt.Errorf("Gunakan klip dengan durasi maksimal %.0f detik.", maxSeconds)
	}
	for _, stream := range p.Streams {
		if stream.Width > 4096 || stream.Height > 4096 {
			return p, 0, errors.New("Resolusi video terlalu besar. Kirim video maksimal 4K.")
		}
	}
	return p, duration, nil
}

func hasStream(p probeResult, kind string) bool {
	for _, s := range p.Streams {
		if s.CodecType == kind {
			return true
		}
	}
	return false
}

func Transcribe(ctx context.Context, data []byte) (string, error) {
	if !Status().Speech {
		return "", errors.New("Pembaca suara lokal belum siap. Silakan kirim pesan teks dulu.")
	}
	if err := acquireAV(ctx); err != nil {
		return "", err
	}
	defer func() { <-avSlots }()
	ctx, cancel := context.WithTimeout(ctx, 120*time.Second)
	defer cancel()
	dir, path, err := tempMedia(data)
	if err != nil {
		return "", err
	}
	defer os.RemoveAll(dir)
	p, _, err := probe(ctx, path, maxAudioSeconds)
	if err != nil {
		return "", err
	}
	if !hasStream(p, "audio") {
		return "", errors.New("Tidak ada suara yang bisa dibaca dari file ini.")
	}
	return transcribePath(ctx, dir, path)
}

func transcribePath(ctx context.Context, dir, path string) (string, error) {
	wav := filepath.Join(dir, "speech.wav")
	_, err := runMedia(ctx, "ffmpeg", "CHATLOOP_FFMPEG", "-v", "error", "-nostdin", "-protocol_whitelist", "file,pipe", "-format_whitelist", allowedFormats, "-i", path, "-map", "0:a:0", "-vn", "-t", strconv.Itoa(maxAudioSeconds), "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", "-threads", "2", wav)
	if err != nil {
		return "", err
	}
	pcm, err := os.ReadFile(wav)
	if err != nil || len(pcm) > 7<<20 {
		return "", errors.New("Suara belum dapat dibaca.")
	}
	if silentWAV(pcm) {
		return "", errors.New("Suara tidak terdengar cukup jelas. Bisa kirim ulang atau tulis pesannya?")
	}
	output := filepath.Join(dir, "transcript")
	args := []string{"-m", modelPath(), "-f", wav, "-l", "auto", "-otxt", "-of", output, "-nt", "-np", "-t", "4", "-p", "1", "-bs", "1", "-bo", "1", "-sns"}
	forceCPU := os.Getenv("CHATLOOP_WHISPER_CPU") == "1"
	if forceCPU {
		args = append(args, "-ng")
	}
	_, err = runMedia(ctx, "whisper-cli", "CHATLOOP_WHISPER_BIN", args...)
	if err != nil && !forceCPU && ctx.Err() == nil {
		// A machine without a usable GPU still supports local speech decoding.
		_, err = runMedia(ctx, "whisper-cli", "CHATLOOP_WHISPER_BIN", append(args, "-ng")...)
	}
	if err != nil {
		return "", err
	}
	f, err := os.Open(output + ".txt")
	if err != nil {
		return "", errors.New("Transkrip suara belum tersedia.")
	}
	defer f.Close()
	out, err := io.ReadAll(io.LimitReader(f, 32001))
	if err != nil || len(out) > 32000 {
		return "", errors.New("Transkrip terlalu panjang. Kirim pesan suara yang lebih pendek.")
	}
	text := strings.TrimSpace(string(out))
	for _, marker := range []string{"[BLANK_AUDIO]", "[ Silence ]", "[silence]", "(silence)", "[Music]", "[MUSIC]"} {
		text = strings.TrimSpace(strings.ReplaceAll(text, marker, ""))
	}
	if len([]rune(text)) < 2 {
		return "", errors.New("Ucapan belum bisa dipahami. Bisa kirim ulang atau tulis pesannya?")
	}
	return text, nil
}

// Reject genuinely silent clips before speech decoding (which can hallucinate on silence).
func silentWAV(data []byte) bool {
	if len(data) < 44 || !bytes.Equal(data[:4], []byte("RIFF")) {
		return true
	}
	for at := 12; at+8 <= len(data); {
		size := int(binary.LittleEndian.Uint32(data[at+4 : at+8]))
		start := at + 8
		if size < 0 || start+size > len(data) {
			return true
		}
		if string(data[at:at+4]) == "data" {
			var energy float64
			count := size / 2
			if count < 1600 {
				return true
			}
			for n := start; n+1 < start+size; n += 2 {
				v := float64(int16(binary.LittleEndian.Uint16(data[n:n+2]))) / 32768
				energy += v * v
			}
			return math.Sqrt(energy/float64(count)) < 0.001
		}
		at = start + size + (size % 2)
	}
	return true
}

func ReadVideo(ctx context.Context, data []byte) (Video, error) {
	if err := acquireAV(ctx); err != nil {
		return Video{}, err
	}
	defer func() { <-avSlots }()
	ctx, cancel := context.WithTimeout(ctx, 150*time.Second)
	defer cancel()
	dir, path, err := tempMedia(data)
	if err != nil {
		return Video{}, err
	}
	defer os.RemoveAll(dir)
	p, duration, err := probe(ctx, path, maxVideoSeconds)
	if err != nil {
		return Video{}, err
	}
	if !hasStream(p, "video") {
		return Video{}, errors.New("Tidak ada gambar video yang bisa dibaca.")
	}
	result := Video{Duration: duration, Note: "Cuplikan berkala; kejadian singkat di antara cuplikan bisa terlewat."}
	for _, at := range frameTimes(duration) {
		out, err := runMedia(ctx, "ffmpeg", "CHATLOOP_FFMPEG", "-v", "error", "-nostdin", "-protocol_whitelist", "file,pipe", "-format_whitelist", allowedFormats, "-ss", fmt.Sprintf("%.3f", at), "-i", path, "-map", "0:v:0", "-an", "-frames:v", "1", "-vf", "scale=640:640:force_original_aspect_ratio=decrease", "-threads", "2", "-q:v", "3", "-f", "image2pipe", "-vcodec", "mjpeg", "pipe:1")
		if err != nil {
			return Video{}, err
		}
		if len(out) > 0 {
			result.Frames = append(result.Frames, Frame{At: at, Data: out})
		}
	}
	if len(result.Frames) == 0 {
		return Video{}, errors.New("Cuplikan video belum bisa dibaca.")
	}
	if hasStream(p, "audio") {
		if Status().Speech {
			result.Transcript, err = transcribePath(ctx, dir, path)
			if err != nil {
				result.Note += " Suara belum terbaca: " + err.Error()
			}
		} else {
			result.Note += " Pembaca suara belum siap; hanya gambar yang dianalisis."
		}
	} else {
		result.Note += " Video tidak memiliki trek suara."
	}
	return result, nil
}

func frameTimes(duration float64) []float64 {
	if duration <= 0 || math.IsNaN(duration) || math.IsInf(duration, 0) {
		return nil
	}
	n := int(math.Ceil(duration/5)) + 1
	if n < 2 {
		n = 2
	}
	if n > 12 {
		n = 12
	}
	last := math.Max(0, duration-0.15)
	out := make([]float64, n)
	for i := range out {
		out[i] = last * float64(i) / float64(n-1)
	}
	return out
}
