// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"bytes"
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"image/jpeg"
	_ "image/png"
	"math"
	"net/http"
	"strings"

	mp4 "github.com/abema/go-mp4"
	xdraw "golang.org/x/image/draw"
	_ "golang.org/x/image/webp"
)

const (
	StatusImageMaxBytes   = 5 << 20
	StatusVideoMaxBytes   = 16 << 20
	StatusVideoMaxSeconds = 90
	StatusTextMaxChars    = 700
	StatusCaptionMaxChars = 1024
)

type StatusMediaInfo struct {
	Kind, Mimetype         string
	Width, Height, Seconds uint32
	Thumbnail              []byte
}

// InspectStatusMedia trusts the file contents, not the browser's Content-Type.
// MP4 parsing reads only bounded metadata boxes, never sample-count allocations.
func InspectStatusMedia(data []byte) (StatusMediaInfo, error) {
	var info StatusMediaInfo
	if len(data) == 0 || len(data) > StatusVideoMaxBytes {
		return info, fmt.Errorf("file kosong atau melebihi batas 16 MB")
	}
	info.Mimetype = http.DetectContentType(data)
	switch info.Mimetype {
	case "image/jpeg", "image/png", "image/webp":
		if len(data) > StatusImageMaxBytes {
			return info, fmt.Errorf("gambar maksimal 5 MB")
		}
		cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
		if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
			return info, fmt.Errorf("gambar tidak dapat dibaca; unggah JPG, PNG, atau WebP yang valid")
		}
		if int64(cfg.Width)*int64(cfg.Height) > 20_000_000 {
			return info, fmt.Errorf("resolusi gambar maksimal 20 megapiksel")
		}
		img, _, err := image.Decode(bytes.NewReader(data))
		if err != nil {
			return info, fmt.Errorf("isi gambar rusak atau tidak lengkap")
		}
		info.Kind, info.Width, info.Height = "image", uint32(cfg.Width), uint32(cfg.Height)
		w, h := 256, max(1, cfg.Height*256/cfg.Width)
		if h > 256 {
			h, w = 256, max(1, cfg.Width*256/cfg.Height)
		}
		thumb := image.NewRGBA(image.Rect(0, 0, w, h))
		draw.Draw(thumb, thumb.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
		xdraw.BiLinear.Scale(thumb, thumb.Bounds(), img, img.Bounds(), draw.Over, nil)
		var encoded bytes.Buffer
		if err := jpeg.Encode(&encoded, thumb, &jpeg.Options{Quality: 75}); err != nil {
			return info, fmt.Errorf("pratinjau gambar gagal disiapkan")
		}
		info.Thumbnail = encoded.Bytes()
		return info, nil
	case "video/mp4":
		return inspectStatusMP4(data)
	default:
		return info, fmt.Errorf("gunakan JPG, PNG, WebP, atau video MP4 (H.264 dengan audio AAC)")
	}
}

func inspectStatusMP4(data []byte) (StatusMediaInfo, error) {
	info := StatusMediaInfo{Kind: "video", Mimetype: "video/mp4"}
	type track struct {
		handler, codec string
		duration       float64
		width, height  uint32
		aac            bool
	}
	var tracks []*track
	var current *track
	var duration float64
	var hasData bool
	boxes := 0
	_, err := mp4.ReadBoxStructure(bytes.NewReader(data), func(h *mp4.ReadHandle) (interface{}, error) {
		boxes++
		if boxes > 2048 || len(h.Path) > 8 || h.BoxInfo.Offset > uint64(len(data)) || h.BoxInfo.Size > uint64(len(data))-h.BoxInfo.Offset {
			return nil, fmt.Errorf("struktur MP4 tidak valid")
		}
		name := h.BoxInfo.Type.String()
		pathParts := make([]string, len(h.Path))
		for i, p := range h.Path {
			pathParts[i] = p.String()
		}
		path := strings.Join(pathParts, "/")
		switch path {
		case "moof", "moov/mvex":
			return nil, fmt.Errorf("ekspor video sebagai MP4 biasa, bukan MP4 terfragmentasi")
		case "mdat":
			hasData = h.BoxInfo.Size > h.BoxInfo.HeaderSize
		case "moov", "moov/trak/mdia", "moov/trak/mdia/minf", "moov/trak/mdia/minf/stbl", "moov/trak/mdia/minf/stbl/stsd":
			return h.Expand()
		case "moov/trak":
			if len(tracks) >= 8 {
				return nil, fmt.Errorf("terlalu banyak track video")
			}
			current = &track{}
			tracks = append(tracks, current)
			return h.Expand()
		case "moov/trak/mdia/minf/stbl/stsd/mp4a":
			if current != nil {
				current.codec = "mp4a"
			}
			return h.Expand()
		case "moov/trak/mdia/minf/stbl/stsd/mp4a/esds":
			if h.BoxInfo.Size > 4096 {
				return nil, fmt.Errorf("metadata audio tidak valid")
			}
			box, _, e := h.ReadPayload()
			if e != nil {
				return nil, e
			}
			if descriptor, ok := box.(*mp4.Esds); ok && current != nil {
				for _, d := range descriptor.Descriptors {
					if d.DecoderConfigDescriptor != nil {
						oti := d.DecoderConfigDescriptor.ObjectTypeIndication
						current.aac = oti == 0x40 || oti == 0x66 || oti == 0x67 || oti == 0x68
					}
				}
			}
		case "moov/mvhd", "moov/trak/mdia/mdhd", "moov/trak/mdia/hdlr", "moov/trak/tkhd":
			if h.BoxInfo.Size > 4096 {
				return nil, fmt.Errorf("metadata MP4 tidak valid")
			}
			box, _, e := h.ReadPayload()
			if e != nil {
				return nil, e
			}
			switch v := box.(type) {
			case *mp4.Mvhd:
				if v.Timescale > 0 {
					duration = float64(v.GetDuration()) / float64(v.Timescale)
				}
			case *mp4.Mdhd:
				if current != nil && v.Timescale > 0 {
					current.duration = float64(v.GetDuration()) / float64(v.Timescale)
				}
			case *mp4.Hdlr:
				if current != nil {
					current.handler = string(v.HandlerType[:])
				}
			case *mp4.Tkhd:
				if current != nil {
					current.width, current.height = uint32(v.GetWidthInt()), uint32(v.GetHeightInt())
				}
			}
		default:
			if strings.HasPrefix(path, "moov/trak/mdia/minf/stbl/stsd/") && len(h.Path) == 7 && current != nil {
				current.codec = name
			}
		}
		return nil, nil
	})
	if err != nil {
		return info, fmt.Errorf("video tidak dapat dibaca: %w", err)
	}
	videos := 0
	for _, t := range tracks {
		duration = math.Max(duration, t.duration)
		switch t.handler {
		case "vide":
			videos++
			if t.codec != "avc1" && t.codec != "avc3" {
				return info, fmt.Errorf("video harus memakai codec H.264; ekspor ulang sebagai MP4 H.264")
			}
			info.Width, info.Height = t.width, t.height
		case "soun":
			if t.codec != "mp4a" || !t.aac {
				return info, fmt.Errorf("audio video harus memakai AAC; ekspor ulang sebagai MP4 H.264/AAC")
			}
		}
	}
	if videos != 1 || !hasData || duration <= 0 || info.Width == 0 || info.Height == 0 {
		return info, fmt.Errorf("MP4 harus berisi satu video dengan durasi yang valid")
	}
	if duration > StatusVideoMaxSeconds {
		return info, fmt.Errorf("durasi video maksimal %d detik; potong video sebelum diunggah", StatusVideoMaxSeconds)
	}
	info.Seconds = uint32(math.Ceil(duration))
	return info, nil
}
