package connector

import (
	"context"
	"net/http"

	"github.com/rs/zerolog"
	"os"
	"testing"
	"time"
)

func TestRegistrableDomain(t *testing.T) {
	cases := map[string]string{
		"user.luma-mail.com":  "luma-mail.com",
		"luma.com":           "luma.com",
		"mail.kleinanzeigen.de": "kleinanzeigen.de",
		"a.b.c.example.co.uk": "example.co.uk",
		"e.stripe.com":       "stripe.com",
		"lists.plattsalat.de": "plattsalat.de",
		"127.0.0.1":          "",
		"":                   "",
	}
	for in, want := range cases {
		if got := registrableDomain(in); got != want {
			t.Errorf("registrableDomain(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestCandidateOrderForLuma(t *testing.T) {
	cands := avatarCandidates("jakobzick@user.luma-mail.com", nil)
	var urls []string
	for _, c := range cands {
		urls = append(urls, c.URL)
	}
	t.Logf("candidates: %v", urls)
	if len(cands) < 13 {
		t.Fatalf("expected at least 9 candidates, got %d", len(cands))
	}
	if !containsSub(urls, "https://luma.com/favicon.ico") {
		t.Errorf("apex-domain fallback missing: %v", urls)
	}
}

func TestICODetection(t *testing.T) {
	// real uber.com favicon layout
	ico := []byte{0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x30, 0x30}
	if !isICO(ico) {
		t.Error("isICO should detect ico header")
	}
	pngHdr := []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a}
	if isICO(pngHdr) {
		t.Error("isICO must not fire on png")
	}
}

func TestGenericAvatarIsPNG(t *testing.T) {
	data := generateGenericAvatar("jakobzick@user.luma-mail.com")
	if http.DetectContentType(data) != "image/png" {
		t.Fatalf("generic avatar is not a png: %s", http.DetectContentType(data))
	}
	if len(data) < 500 {
		t.Fatalf("generic avatar suspiciously small: %d bytes", len(data))
	}
	if err := os.WriteFile("/tmp/opencode/generic-luma.png", data, 0o644); err != nil {
		t.Fatal(err)
	}
	t.Logf("generic avatar: %d bytes -> /tmp/opencode/generic-luma.png", len(data))

	// determinism
	again := generateGenericAvatar("jakobzick@user.luma-mail.com")
	if string(again) != string(data) {
		t.Error("generic avatar is not deterministic")
	}
	other := generateGenericAvatar("someone@else.com")
	if string(other) == string(data) {
		t.Error("different addresses produced identical avatars")
	}
}

func TestNormalizeRejectsSVG(t *testing.T) {
	svg := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10"/></svg>`)
	svg = append(svg, make([]byte, 100)...)
	if _, err := normalizeAvatarImage(svg); err == nil {
		t.Error("svg should be rejected")
	}
	if _, err := normalizeAvatarImage([]byte("<html>hello</html>------------------")); err == nil {
		t.Error("html should be rejected")
	}
}

// Live test: only run when AVDATA is set to "1" to avoid network in CI.
func TestLiveLuma(t *testing.T) {
	if os.Getenv("AVDATA") != "1" {
		t.Skip("set AVDATA=1")
	}
	mc := &MailClient{Log: zerolog.Nop()}
	av := mc.avatarFor("jakobzick@user.luma-mail.com")
	ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
	defer cancel()
	data, err := av.Get(ctx)
	if err != nil {
		t.Fatalf("live fetch failed: %v", err)
	}
	t.Logf("jakobzick@user.luma-mail.com -> %d bytes, %s", len(data), http.DetectContentType(data))
	if err := os.WriteFile("/tmp/opencode/live-jakobzick.png", data, 0o644); err != nil {
		t.Fatal(err)
	}
}

func containsSub(hay []string, needle string) bool {
	for _, h := range hay {
		if h == needle {
			return true
		}
	}
	return false
}

func TestLiveUberICO(t *testing.T) {
	if os.Getenv("AVDATA") != "1" {
		t.Skip("set AVDATA=1")
	}
	mc := &MailClient{Log: zerolog.Nop()}
	av := mc.avatarFor("noreply@uber.com")
	ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
	defer cancel()
	data, err := av.Get(ctx)
	if err != nil {
		t.Fatalf("live fetch failed: %v", err)
	}
	mime := http.DetectContentType(data)
	t.Logf("noreply@uber.com -> %d bytes, %s", len(data), mime)
	if mime != "image/png" {
		t.Fatalf("expected png after ico conversion, got %s", mime)
	}
	_ = os.WriteFile("/tmp/opencode/live-uber.png", data, 0o644)
}

func TestLiveHetznerICO(t *testing.T) {
	if os.Getenv("AVDATA") != "1" {
		t.Skip("set AVDATA=1")
	}
	mc := &MailClient{Log: zerolog.Nop()}
	av := mc.avatarFor("noreply.billing@hetzner.com")
	ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
	defer cancel()
	data, err := av.Get(ctx)
	if err != nil {
		t.Fatalf("live fetch failed: %v", err)
	}
	mime := http.DetectContentType(data)
	t.Logf("noreply.billing@hetzner.com -> %d bytes, %s", len(data), mime)
	_ = os.WriteFile("/tmp/opencode/live-hetzner.png", data, 0o644)
}

func TestLiveMesseJobs(t *testing.T) {
	if os.Getenv("AVDATA") != "1" {
		t.Skip("set AVDATA=1")
	}
	mc := &MailClient{Log: zerolog.Nop()}
	av := mc.avatarFor("bewerbung5@messe-jobs.de")
	ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
	defer cancel()
	data, err := av.Get(ctx)
	if err != nil {
		t.Fatalf("live fetch failed: %v", err)
	}
	t.Logf("bewerbung5@messe-jobs.de -> %d bytes, %s", len(data), http.DetectContentType(data))
}

func TestDomainGhostGetsFavicon(t *testing.T) {
	cands := avatarCandidates("user.luma-mail.com", nil)
	var urls []string
	for _, c := range cands {
		urls = append(urls, c.URL)
	}
	t.Logf("domain-ghost candidates: %d %v", len(cands), urls)
	if !containsSub(urls, "https://luma.com/favicon.ico") {
		t.Fatalf("domain ghost did not get the luma.com alias: %v", urls)
	}
	if len(avatarCandidates("not a domain", nil)) != 1 {
		t.Error("garbage string should only get gravatar")
	}
}
