package pipeline

import (
	"context"
	"errors"
	"reflect"
	"strings"
	"testing"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
)

func registerTestInput(registry *InputAdapterRegistry, key string, constructor InputAdapterConstructor) error {
	return registry.RegisterWithSpec(testModuleSpec(key, StageInput), constructor)
}

func TestInputAdapterRegistryRegisterAndBuild(t *testing.T) {
	registry := NewInputAdapterRegistry()

	if err := registerTestInput(registry, "generic-input", fakeInputAdapterConstructor("generic-input")); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	adapter, err := registry.Build("generic-input")
	if err != nil {
		t.Fatalf("Build() error = %v, want nil", err)
	}
	if adapter.Key() != "generic-input" {
		t.Fatalf("adapter.Key() = %q, want generic-input", adapter.Key())
	}
}

func TestInputAdapterRegistryRegisterAndBuildTrimKeys(t *testing.T) {
	registry := NewInputAdapterRegistry()

	if err := registerTestInput(registry, " generic-input ", fakeInputAdapterConstructor("generic-input")); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	adapter, err := registry.Build("\tgeneric-input\n")
	if err != nil {
		t.Fatalf("Build() error = %v, want nil", err)
	}
	if adapter.Key() != "generic-input" {
		t.Fatalf("adapter.Key() = %q, want generic-input", adapter.Key())
	}
}

func TestInputAdapterRegistryRegisterWithSpecStoresMetadata(t *testing.T) {
	registry := NewInputAdapterRegistry()
	spec := ModuleSpec{
		Key:            " generic-input ",
		Stage:          StageInput,
		ExecutionClass: contracts.ExecutionClassDeterministic,
		Provides:       []string{" parsed-source ", "source-document", "parsed-source", ""},
		Requires:       []string{" raw-bytes ", "raw-bytes", ""},
	}

	if err := registry.RegisterWithSpec(spec, fakeInputAdapterConstructor("generic-input")); err != nil {
		t.Fatalf("RegisterWithSpec() error = %v, want nil", err)
	}

	got, ok := registry.Spec("\tgeneric-input\n")
	if !ok {
		t.Fatal("Spec() ok = false, want true")
	}
	want := ModuleSpec{
		Key:            "generic-input",
		Stage:          StageInput,
		ExecutionClass: contracts.ExecutionClassDeterministic,
		Provides:       []string{"parsed-source", "source-document"},
		Requires:       []string{"raw-bytes"},
	}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("Spec() = %#v, want %#v", got, want)
	}

	got.Provides[0] = "changed"
	again, ok := registry.Spec("generic-input")
	if !ok {
		t.Fatal("Spec() after caller mutation ok = false, want true")
	}
	if !reflect.DeepEqual(again, want) {
		t.Fatalf("Spec() after caller mutation = %#v, want %#v", again, want)
	}
}

func TestInputAdapterRegistryRegisterWithSpecStoresMinimalMetadata(t *testing.T) {
	registry := NewInputAdapterRegistry()

	if err := registerTestInput(registry, " generic-input ", fakeInputAdapterConstructor("generic-input")); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	got, ok := registry.Spec("generic-input")
	if !ok {
		t.Fatal("Spec() ok = false, want true")
	}
	want := ModuleSpec{Key: "generic-input", Stage: StageInput, ExecutionClass: contracts.ExecutionClassDeterministic}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("Spec() = %#v, want %#v", got, want)
	}
}

func TestInputAdapterRegistryRegisterWithSpecRejectsWrongStage(t *testing.T) {
	registry := NewInputAdapterRegistry()

	err := registry.RegisterWithSpec(ModuleSpec{Key: "generic-input", Stage: StageExtract, ExecutionClass: contracts.ExecutionClassDeterministic}, fakeInputAdapterConstructor("generic-input"))

	if err == nil {
		t.Fatal("RegisterWithSpec() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "stage") {
		t.Fatalf("RegisterWithSpec() error = %q, want stage error", err.Error())
	}
}

func TestInputAdapterRegistrySpecRejectsUnknownKey(t *testing.T) {
	registry := NewInputAdapterRegistry()

	if _, ok := registry.Spec("missing-input"); ok {
		t.Fatal("Spec() ok = true, want false")
	}
}

func TestInputAdapterRegistryRegisterRejectsEmptyKey(t *testing.T) {
	registry := NewInputAdapterRegistry()

	err := registerTestInput(registry, " \t", fakeInputAdapterConstructor("generic-input"))

	if err == nil {
		t.Fatal("Register() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "key must not be empty") {
		t.Fatalf("Register() error = %q, want empty key error", err.Error())
	}
}

func TestInputAdapterRegistryRegisterRejectsDuplicateKey(t *testing.T) {
	registry := NewInputAdapterRegistry()
	if err := registerTestInput(registry, "generic-input", fakeInputAdapterConstructor("generic-input")); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	err := registerTestInput(registry, " generic-input ", fakeInputAdapterConstructor("generic-input"))

	if err == nil {
		t.Fatal("Register() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "already registered") {
		t.Fatalf("Register() error = %q, want duplicate key error", err.Error())
	}
}

func TestInputAdapterRegistryRegisterRejectsNilConstructor(t *testing.T) {
	registry := NewInputAdapterRegistry()

	err := registerTestInput(registry, "generic-input", nil)

	if err == nil {
		t.Fatal("Register() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "constructor") {
		t.Fatalf("Register() error = %q, want constructor error", err.Error())
	}
}

func TestInputAdapterRegistryBuildRejectsUnknownKey(t *testing.T) {
	registry := NewInputAdapterRegistry()

	_, err := registry.Build("missing-input")

	if err == nil {
		t.Fatal("Build() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "not registered") {
		t.Fatalf("Build() error = %q, want unknown key error", err.Error())
	}
}

func TestInputAdapterRegistryBuildWrapsConstructorError(t *testing.T) {
	registry := NewInputAdapterRegistry()
	constructorErr := errors.New("constructor failed")
	if err := registerTestInput(registry, "generic-input", func() (contracts.InputAdapter, error) {
		return nil, constructorErr
	}); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	_, err := registry.Build("generic-input")

	if err == nil {
		t.Fatal("Build() error = nil, want error")
	}
	if !errors.Is(err, constructorErr) {
		t.Fatalf("Build() error = %v, want wrapped constructor error", err)
	}
	if !strings.Contains(err.Error(), "generic-input") {
		t.Fatalf("Build() error = %q, want key context", err.Error())
	}
}

func TestInputAdapterRegistryBuildRejectsNilAdapter(t *testing.T) {
	registry := NewInputAdapterRegistry()
	if err := registerTestInput(registry, "generic-input", func() (contracts.InputAdapter, error) {
		return nil, nil
	}); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	_, err := registry.Build("generic-input")

	if err == nil {
		t.Fatal("Build() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "returned nil") {
		t.Fatalf("Build() error = %q, want nil adapter error", err.Error())
	}
}

func TestInputAdapterRegistryBuildRejectsAdapterKeyMismatch(t *testing.T) {
	registry := NewInputAdapterRegistry()
	if err := registerTestInput(registry, "generic-input", fakeInputAdapterConstructor("other-input")); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	_, err := registry.Build("generic-input")

	if err == nil {
		t.Fatal("Build() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "returned key") {
		t.Fatalf("Build() error = %q, want key mismatch error", err.Error())
	}
}

func TestInputAdapterRegistryRegisteredKeysReturnsSortedCopy(t *testing.T) {
	registry := NewInputAdapterRegistry()
	for _, key := range []string{"zeta", "alpha", "middle"} {
		if err := registerTestInput(registry, key, fakeInputAdapterConstructor(key)); err != nil {
			t.Fatalf("Register(%q) error = %v, want nil", key, err)
		}
	}

	keys := registry.RegisteredKeys()

	want := []string{"alpha", "middle", "zeta"}
	if !reflect.DeepEqual(keys, want) {
		t.Fatalf("RegisteredKeys() = %#v, want %#v", keys, want)
	}

	keys[0] = "changed"
	if got := registry.RegisteredKeys(); !reflect.DeepEqual(got, want) {
		t.Fatalf("RegisteredKeys() after caller mutation = %#v, want %#v", got, want)
	}
}

func TestInputAdapterRegistryNilRegistryBehavior(t *testing.T) {
	var registry *InputAdapterRegistry

	if err := registerTestInput(registry, "generic-input", fakeInputAdapterConstructor("generic-input")); err == nil {
		t.Fatal("Register() error = nil, want error")
	}
	if _, err := registry.Build("generic-input"); err == nil {
		t.Fatal("Build() error = nil, want error")
	}
	if _, ok := registry.Spec("generic-input"); ok {
		t.Fatal("Spec() ok = true, want false")
	}
	if keys := registry.RegisteredKeys(); keys != nil {
		t.Fatalf("RegisteredKeys() = %#v, want nil", keys)
	}
}

func TestInputAdapterRegistryBuildRejectsEmptyKey(t *testing.T) {
	registry := NewInputAdapterRegistry()

	_, err := registry.Build(" \n")

	if err == nil {
		t.Fatal("Build() error = nil, want error")
	}
	if !strings.Contains(err.Error(), "key must not be empty") {
		t.Fatalf("Build() error = %q, want empty key error", err.Error())
	}
}

type fakeAdapter struct {
	key string
}

func fakeInputAdapterConstructor(key string) InputAdapterConstructor {
	return func() (contracts.InputAdapter, error) {
		return fakeAdapter{key: key}, nil
	}
}

func (adapter fakeAdapter) Key() string {
	return adapter.key
}

func (adapter fakeAdapter) Parse(ctx context.Context, req contracts.ParseRequest) (*source.SourceDocument, error) {
	return &source.SourceDocument{
		ID:     req.SourceID,
		Kind:   "document",
		Format: "text/plain",
		Digest: "sha256:abc123",
		Units: []source.SourceUnit{
			{ID: 1, Kind: "unit", Text: "Source unit.", Ref: source.SourceRef{SourceID: req.SourceID, StartUnitID: 1, EndUnitID: 1}},
		},
	}, nil
}
