// Package logo normalizes an uploaded group or repository logo.
// Raster images larger than 512×512 are scaled down, keeping the
// aspect ratio. SVG is kept as text when it is small and has no script.
package logo

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"image"
	"image/color"
	_ "image/gif"
	_ "image/jpeg"
	"image/png"
	"io"
	"math"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/i18n"
)

const (
	MaxEdge   = 512
	MaxSVG    = 256 << 10
	MaxUpload = 2 << 20
)

// Normalize returns bytes and a content type ready to store.
func Normalize(in []byte) ([]byte, string, error) {
	if len(in) == 0 || len(in) > MaxUpload {
		return nil, "", i18n.E("err.logoBig")
	}
	if looksSVG(in) {
		if len(in) > MaxSVG {
			return nil, "", i18n.E("err.logoBig")
		}
		if err := vetSVG(in); err != nil {
			return nil, "", err
		}
		return in, "image/svg+xml", nil
	}
	img, _, err := image.Decode(bytes.NewReader(in))
	if err != nil {
		return nil, "", i18n.E("err.logoType")
	}
	b := img.Bounds()
	w, h := b.Dx(), b.Dy()
	if w < 1 || h < 1 {
		return nil, "", i18n.E("err.logoType")
	}
	nw, nh := fit(w, h)
	var src image.Image = img
	if nw != w || nh != h {
		src = scale(img, nw, nh)
	}
	var buf bytes.Buffer
	if err := png.Encode(&buf, src); err != nil {
		return nil, "", i18n.E("err.logoStore")
	}
	return buf.Bytes(), "image/png", nil
}

func fit(w, h int) (int, int) {
	if w <= MaxEdge && h <= MaxEdge {
		return w, h
	}
	s := float64(MaxEdge) / float64(w)
	if float64(h)*s > MaxEdge {
		s = float64(MaxEdge) / float64(h)
	}
	nw := int(math.Round(float64(w) * s))
	nh := int(math.Round(float64(h) * s))
	if nw < 1 {
		nw = 1
	}
	if nh < 1 {
		nh = 1
	}
	if nw > MaxEdge {
		nw = MaxEdge
	}
	if nh > MaxEdge {
		nh = MaxEdge
	}
	return nw, nh
}

func scale(src image.Image, nw, nh int) *image.NRGBA {
	dst := image.NewNRGBA(image.Rect(0, 0, nw, nh))
	sb := src.Bounds()
	sw, sh := float64(sb.Dx()), float64(sb.Dy())
	for y := 0; y < nh; y++ {
		sy := (float64(y)+0.5)*sh/float64(nh) - 0.5
		for x := 0; x < nw; x++ {
			sx := (float64(x)+0.5)*sw/float64(nw) - 0.5
			dst.SetNRGBA(x, y, bilinear(src, sb, sx, sy))
		}
	}
	return dst
}

func bilinear(src image.Image, b image.Rectangle, x, y float64) color.NRGBA {
	x0 := int(math.Floor(x))
	y0 := int(math.Floor(y))
	fx := x - float64(x0)
	fy := y - float64(y0)
	c00 := nrgbaAt(src, b, x0, y0)
	c10 := nrgbaAt(src, b, x0+1, y0)
	c01 := nrgbaAt(src, b, x0, y0+1)
	c11 := nrgbaAt(src, b, x0+1, y0+1)
	mix := func(a, b, c, d uint8) uint8 {
		top := float64(a)*(1-fx) + float64(b)*fx
		bot := float64(c)*(1-fx) + float64(d)*fx
		return uint8(math.Round(top*(1-fy) + bot*fy))
	}
	return color.NRGBA{
		R: mix(c00.R, c10.R, c01.R, c11.R),
		G: mix(c00.G, c10.G, c01.G, c11.G),
		B: mix(c00.B, c10.B, c01.B, c11.B),
		A: mix(c00.A, c10.A, c01.A, c11.A),
	}
}

func nrgbaAt(src image.Image, b image.Rectangle, x, y int) color.NRGBA {
	if x < b.Min.X {
		x = b.Min.X
	}
	if y < b.Min.Y {
		y = b.Min.Y
	}
	if x >= b.Max.X {
		x = b.Max.X - 1
	}
	if y >= b.Max.Y {
		y = b.Max.Y - 1
	}
	r, g, bl, a := src.At(x, y).RGBA()
	return color.NRGBA{R: uint8(r >> 8), G: uint8(g >> 8), B: uint8(bl >> 8), A: uint8(a >> 8)}
}

func looksSVG(in []byte) bool {
	s := strings.ToLower(strings.TrimSpace(string(in)))
	return strings.HasPrefix(s, "<svg") || strings.HasPrefix(s, "<?xml") || strings.HasPrefix(s, "<!doctype")
}

func vetSVG(in []byte) error {
	low := strings.ToLower(string(in))
	if !strings.Contains(low, "<svg") {
		return i18n.E("err.logoType")
	}
	for _, bad := range []string{"<script", "foreignobject", "onload", "onerror", "javascript:", "<iframe", "<object", "<embed"} {
		if strings.Contains(low, bad) {
			return i18n.E("err.logoSVG")
		}
	}
	dec := xml.NewDecoder(bytes.NewReader(in))
	saw := false
	for {
		tok, err := dec.Token()
		if err == io.EOF {
			break
		}
		if err != nil {
			return i18n.E("err.logoSVG")
		}
		se, ok := tok.(xml.StartElement)
		if !ok {
			continue
		}
		if strings.EqualFold(se.Name.Local, "svg") {
			saw = true
		}
	}
	if !saw {
		return i18n.E("err.logoType")
	}
	return nil
}

// SizeOf decodes a PNG or other raster and returns its pixel size.
func SizeOf(in []byte) (int, int, error) {
	cfg, _, err := image.DecodeConfig(bytes.NewReader(in))
	if err != nil {
		return 0, 0, fmt.Errorf("decode: %w", err)
	}
	return cfg.Width, cfg.Height, nil
}
