package clients

import (
	"context"
	"io"
	"net/http"
	"testing"
	"time"
)

type timeoutResponseBody struct {
	read bool
}

func (body *timeoutResponseBody) Read(buffer []byte) (int, error) {
	if body.read {
		return 0, context.DeadlineExceeded
	}
	body.read = true
	return copy(buffer, []byte(`{"partial":`)), nil
}

func (*timeoutResponseBody) Close() error { return nil }

func TestProviderRequestTimeoutUsesMediaDefaults(t *testing.T) {
	for _, test := range []struct {
		kind string
		want time.Duration
	}{
		{kind: "images.generations", want: 20 * time.Minute},
		{kind: "images.edits", want: 20 * time.Minute},
		{kind: "videos.generations", want: 30 * time.Minute},
		{kind: "chat.completions", want: 10 * time.Minute},
	} {
		if got := ProviderRequestTimeout(test.kind); got != test.want {
			t.Fatalf("timeout for %s: got %s want %s", test.kind, got, test.want)
		}
	}
}

func TestTransportTimeoutUsesTerminalTimeoutCode(t *testing.T) {
	err := transportClientError(context.DeadlineExceeded)
	if err.Code != "timeout" || err.Retryable {
		t.Fatalf("transport timeout classification = %+v, want terminal timeout", err)
	}
}

func TestResponseBodyTimeoutUsesTerminalTimeoutCode(t *testing.T) {
	response := &http.Response{
		StatusCode: http.StatusOK,
		Header:     make(http.Header),
		Body:       io.NopCloser(&timeoutResponseBody{}),
	}
	_, wire, err := decodeHTTPResponseForProtocol(response, ProtocolOpenAIImages)
	if err == nil {
		t.Fatal("expected response body timeout")
	}
	clientErr, ok := err.(*ClientError)
	if !ok || clientErr.Code != "timeout" || clientErr.Retryable {
		t.Fatalf("response body timeout classification = %#v, want terminal timeout", err)
	}
	if clientErr.StatusCode != http.StatusOK || clientErr.Wire != wire {
		t.Fatalf("response body timeout lost response metadata: %#v", clientErr)
	}
}

func TestMediaPollTimeoutsUseTaskDefaultsWithoutPlatformOverride(t *testing.T) {
	image := Request{Kind: "images.generations", Candidate: storeCandidateWithConfig("", "", nil, nil)}
	video := Request{Kind: "videos.generations", Candidate: storeCandidateWithConfig("", "", nil, nil)}
	if got := providerPollTimeout(image); got != 20*time.Minute {
		t.Fatalf("image provider poll timeout: got %s want %s", got, 20*time.Minute)
	}
	if got := providerPollTimeout(video); got != 30*time.Minute {
		t.Fatalf("video provider poll timeout: got %s want %s", got, 30*time.Minute)
	}
	if got := kelingPollTimeout(video); got != 30*time.Minute {
		t.Fatalf("Keling video poll timeout: got %s want %s", got, 30*time.Minute)
	}
	if got := volcesPollTimeout(video); got != 30*time.Minute {
		t.Fatalf("Volces video poll timeout: got %s want %s", got, 30*time.Minute)
	}
}
