// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

// Package customermedia prepares bounded, local input for the conversation AI.
// Speech is transcribed locally; customer files never become business knowledge.
package customermedia

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"time"
)

const modelName = "ggml-small-q5_1.bin"
const modelHash = "ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bb"
const modelBytes = 190085487
const modelURL = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/" + modelName

type RuntimeInfo struct {
	State     string `json:"state"`
	Message   string `json:"message"`
	Speech    bool   `json:"speech"`
	Video     bool   `json:"video"`
	Documents bool   `json:"documents"`
	Model     string `json:"model"`
}

var runtimeState = struct {
	sync.RWMutex
	started        bool
	state, message string
}{state: "checking", message: "Memeriksa pembaca media lokal."}

func findBinary(name, env string) string {
	if configured := strings.TrimSpace(os.Getenv(env)); configured != "" {
		if found, err := exec.LookPath(configured); err == nil {
			return found
		}
		return ""
	}
	ext := ""
	if runtime.GOOS == "windows" {
		ext = ".exe"
	}
	if found, err := exec.LookPath(name + ext); err == nil {
		return found
	}
	for _, path := range []string{filepath.Join("data", "media-runtime", "bin", name+ext), filepath.Join("/opt/homebrew/bin", name+ext), filepath.Join("/usr/local/bin", name+ext)} {
		if found, err := exec.LookPath(path); err == nil {
			return found
		}
	}
	return ""
}

func modelPath() string {
	if configured := strings.TrimSpace(os.Getenv("CHATLOOP_WHISPER_MODEL")); configured != "" {
		return configured
	}
	return filepath.Join("data", "media-runtime", modelName)
}

func Status() RuntimeInfo {
	runtimeState.RLock()
	state, message := runtimeState.state, runtimeState.message
	runtimeState.RUnlock()
	tools := findBinary("ffmpeg", "CHATLOOP_FFMPEG") != "" && findBinary("ffprobe", "CHATLOOP_FFPROBE") != ""
	speech := state == "ready" && tools && findBinary("whisper-cli", "CHATLOOP_WHISPER_BIN") != ""
	return RuntimeInfo{State: state, Message: message, Speech: speech, Video: tools, Documents: true, Model: "Whisper small multilingual (lokal)"}
}

func setState(state, message string) {
	runtimeState.Lock()
	runtimeState.state, runtimeState.message = state, message
	runtimeState.Unlock()
}

// Start downloads verified weights in the background, never on the Inbox request.
// Executables are supplied by the installation; the server never runs a package manager.
func Start(ctx context.Context) {
	runtimeState.Lock()
	if runtimeState.started {
		runtimeState.Unlock()
		return
	}
	runtimeState.started = true
	runtimeState.Unlock()
	go func() {
		if findBinary("ffmpeg", "CHATLOOP_FFMPEG") == "" || findBinary("ffprobe", "CHATLOOP_FFPROBE") == "" || findBinary("whisper-cli", "CHATLOOP_WHISPER_BIN") == "" {
			setState("unavailable", "Pembaca suara memerlukan FFmpeg dan whisper.cpp di mesin ChatLoop.")
			return
		}
		setState("preparing", "Menyiapkan model transkripsi lokal; unduhan hanya diperlukan sekali.")
		if err := prepareModel(ctx); err != nil {
			setState("error", "Model suara belum siap. Periksa koneksi dan ruang penyimpanan, lalu jalankan ulang ChatLoop.")
			return
		}
		setState("ready", "Suara dibaca di mesin ChatLoop. Video menggunakan cuplikan gambar dan transkrip suara.")
	}()
}

func validModel(path string) bool {
	f, err := os.Open(path)
	if err != nil {
		return false
	}
	defer f.Close()
	if strings.TrimSpace(os.Getenv("CHATLOOP_WHISPER_MODEL")) != "" {
		info, err := f.Stat()
		return err == nil && info.Size() > 1<<20
	}
	h := sha256.New()
	n, err := io.Copy(h, io.LimitReader(f, modelBytes+1))
	return err == nil && n == modelBytes && hex.EncodeToString(h.Sum(nil)) == modelHash
}

func prepareModel(ctx context.Context) error {
	path := modelPath()
	if validModel(path) {
		return nil
	}
	if strings.TrimSpace(os.Getenv("CHATLOOP_WHISPER_MODEL")) != "" {
		return fmt.Errorf("configured model unavailable")
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return err
	}
	ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, modelURL, nil)
	if err != nil {
		return err
	}
	resp, err := (&http.Client{Timeout: 10 * time.Minute}).Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("model download unavailable")
	}
	f, err := os.CreateTemp(filepath.Dir(path), "whisper-download-*")
	if err != nil {
		return err
	}
	name := f.Name()
	defer os.Remove(name)
	_, err = io.Copy(f, io.LimitReader(resp.Body, modelBytes+1))
	closeErr := f.Close()
	if err != nil || closeErr != nil || !validModel(name) {
		return fmt.Errorf("model integrity check failed")
	}
	return os.Rename(name, path)
}
