package task

import (
	"context"
	"testing"
	"text/template"

	"github.com/stretchr/testify/assert"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/utils/ptr"
	"sigs.k8s.io/controller-runtime/pkg/client"

	agentv2 "github.com/tidbcloud/observability/agent-control-server/api/v2"
	"github.com/tidbcloud/observability/agent-control-server/pkg/config"
	"github.com/tidbcloud/observability/agent-control-server/pkg/consts"
	"github.com/tidbcloud/observability/agent-control-server/pkg/reconciler"
	"github.com/tidbcloud/observability/agent-control-server/pkg/testkits"
)

func makeVectorTask(agent *agentv2.KubernetesAgent, opts testkits.TaskOptions) *VectorTask {
	objs := []client.Object{agent}
	if len(opts.LocalObjects) > 0 {
		objs = append(objs, opts.LocalObjects...)
	}
	localCli := testkits.BuildClient(objs...)

	ctx := &reconciler.Context[*agentv2.KubernetesAgent]{
		Agent:     agent,
		Local:     localCli,
		Remote:    testkits.NewClientGetterWithOpts(opts),
		Config:    &opts.Config,
		Templates: opts.Templates,
	}
	return NewVectorTask(ctx)
}

func baseVectorConfig() config.RootConfig {
	return config.RootConfig{
		O11yConfig: config.ObservabilityInfra{
			Vendor: "aws",
			CustomerConfigsV2: config.CustomerConfigsV2{
				NextGen: config.CustomerNextGen{
					K8s: config.CustomerNextGenK8s{
						Default: config.CustomerAgents{
							Vector: &config.VectorConfig{
								Chart: &config.CustomerHelmChart{
									Name:    "vector",
									Version: "1.0.0",
								},
								Image: "vectorio/vector:latest",
							},
						},
						Specs: config.CustomerAgentSpecs{
							{
								Name:   "default",
								Vector: &corev1.ResourceRequirements{},
							},
						},
					},
				},
			},
		},
	}
}

func TestVectorTask(t *testing.T) {
	tests := []struct {
		name   string
		verify func(t *testing.T)
	}{
		{
			name: "Name",
			verify: func(t *testing.T) {
				task := &VectorTask{}
				assert.Equal(t, "Vector", task.Name())
			},
		},
		{
			name: "ClusterMeta",
			verify: func(t *testing.T) {
				agent := testkits.NewKubernetesAgentBuilder().Build()
				task := makeVectorTask(agent, testkits.TaskOptions{})
				meta := task.ClusterMeta()

				assert.Equal(t, consts.AgentKubernetes, meta.Agent)
				assert.Equal(t, "test-cluster", meta.K8sClusterName)
				assert.Equal(t, "tenant-1", meta.TenantID)
				assert.Equal(t, "app-1", meta.ApplicationID)
				assert.Equal(t, "tidbcloud", meta.BizType)
			},
		},
		{
			name: "buildNamespace normal mode",
			verify: func(t *testing.T) {
				agent := testkits.NewKubernetesAgentBuilder().Build()
				task := makeVectorTask(agent, testkits.TaskOptions{Config: baseVectorConfig()})
				assert.Equal(t, consts.O11ySystemNamespace, task.buildNamespace())
			},
		},
		{
			name: "buildNamespace serverless mode",
			verify: func(t *testing.T) {
				cfg := baseVectorConfig()
				cfg.Mode = config.ModeServerless
				agent := testkits.NewKubernetesAgentBuilder().Build()
				task := makeVectorTask(agent, testkits.TaskOptions{Config: cfg})
				assert.Equal(t, consts.ServerlessObservabilityNamespace, task.buildNamespace())
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.verify(t)
		})
	}
}

func TestVectorTask_Create(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.KubernetesAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "create fails with helm config error",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{HelmError: true, Config: baseVectorConfig()},
			wantErr: true,
		},
		{
			name:    "create fails with missing template",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient(), Config: baseVectorConfig()},
			wantErr: true,
		},
		{
			name:  "create fails with alicloud vendor when secret not found",
			agent: testkits.NewKubernetesAgentBuilder().Build(),
			opts: func() testkits.TaskOptions {
				cfg := baseVectorConfig()
				cfg.O11yConfig.Vendor = "alicloud"
				return testkits.TaskOptions{Client: testkits.BuildClient(), Config: cfg}
			}(),
			wantErr: true,
		},
		{
			name: "create fails when spec not found",
			agent: testkits.NewKubernetesAgentBuilder().
				WithAnnotations(map[string]string{consts.AnnotationKeyO11yDesiredSpec: "nonexistent"}).
				Build(),
			opts: func() testkits.TaskOptions {
				cfg := baseVectorConfig()
				cfg.O11yConfig.CustomerConfigsV2.NextGen.K8s.Specs = nil
				return testkits.TaskOptions{HelmError: true, Config: cfg}
			}(),
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVectorTask(tt.agent, tt.opts)
			result := task.Create(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}

func TestVectorTask_PostCreate(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.KubernetesAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "post create fails with remote client error",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "post create fails when daemonset not ready",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: true,
		},
		{
			name:  "post create succeeds when daemonset ready",
			agent: testkits.NewKubernetesAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&appsv1.DaemonSet{
						ObjectMeta: metav1.ObjectMeta{
							Name:      consts.O11yNameVector,
							Namespace: consts.O11ySystemNamespace,
						},
						Spec:   appsv1.DaemonSetSpec{},
						Status: appsv1.DaemonSetStatus{DesiredNumberScheduled: 1, NumberReady: 1},
					},
				),
			},
			wantErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVectorTask(tt.agent, tt.opts)
			result := task.PostCreate(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}

func TestVectorTask_PostDelete(t *testing.T) {
	tests := []struct {
		name    string
		agent   *agentv2.KubernetesAgent
		opts    testkits.TaskOptions
		wantErr bool
	}{
		{
			name:    "post delete fails with remote client error",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{ClientError: true},
			wantErr: true,
		},
		{
			name:    "post delete succeeds when daemonset deleted",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Client: testkits.BuildClient()},
			wantErr: false,
		},
		{
			name:  "post delete fails when daemonset still exists",
			agent: testkits.NewKubernetesAgentBuilder().Build(),
			opts: testkits.TaskOptions{
				Client: testkits.BuildClient(
					&appsv1.DaemonSet{
						ObjectMeta: metav1.ObjectMeta{
							Name:      consts.O11yNameVector,
							Namespace: consts.O11ySystemNamespace,
						},
					},
				),
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVectorTask(tt.agent, tt.opts)
			result := task.PostDelete(context.Background())
			if tt.wantErr {
				assert.Error(t, result.Error())
			} else {
				assert.NoError(t, result.Error())
			}
		})
	}
}

func TestVectorTask_build(t *testing.T) {
	tmpl, err := template.New("test").Parse(`
{{with index . "PodHostNetwork"}}podHostNetwork: {{.}}
{{end}}{{with index . "DNSPolicy"}}dnsPolicy: {{.}}
{{end -}}
image: {{.ImageRepo}}:{{.ImageTag}}
accessKey: {{.AccessKeyID}}
secretKey: {{.SecretAccessKey}}
region: {{.Region}}
bucket: {{.Bucket}}
roleARN: {{.RoleARN}}
`)
	assert.NoError(t, err)

	tests := []struct {
		name        string
		agent       *agentv2.KubernetesAgent
		opts        testkits.TaskOptions
		wantErr     bool
		errMsg      string
		outContains []string
		outExcludes []string
	}{
		{
			name:        "build succeeds with aws vendor",
			agent:       testkits.NewKubernetesAgentBuilder().Build(),
			opts:        testkits.TaskOptions{Config: baseVectorConfig(), Templates: config.Templates{"k8s/vector-values-aws.yaml": tmpl}},
			outContains: []string{"vectorio/vector:latest"},
			outExcludes: []string{"podHostNetwork:", "dnsPolicy:"},
		},
		{
			name:  "build renders configured network values",
			agent: testkits.NewKubernetesAgentBuilder().Build(),
			opts: func() testkits.TaskOptions {
				cfg := baseVectorConfig()
				cfg.O11yConfig.CustomerConfigsV2.NextGen.K8s.Default.Vector.PodHostNetwork = ptr.To(true)
				cfg.O11yConfig.CustomerConfigsV2.NextGen.K8s.Default.Vector.DNSPolicy = string(corev1.DNSClusterFirstWithHostNet)
				return testkits.TaskOptions{Config: cfg, Templates: config.Templates{"k8s/vector-values-aws.yaml": tmpl}}
			}(),
			outContains: []string{"podHostNetwork: true", "dnsPolicy: ClusterFirstWithHostNet"},
		},
		{
			name:    "build fails with missing template",
			agent:   testkits.NewKubernetesAgentBuilder().Build(),
			opts:    testkits.TaskOptions{Config: baseVectorConfig()},
			wantErr: true,
		},
		{
			name:  "build fails with alicloud vendor when secret not found",
			agent: testkits.NewKubernetesAgentBuilder().Build(),
			opts: func() testkits.TaskOptions {
				cfg := baseVectorConfig()
				cfg.O11yConfig.Vendor = "alicloud"
				return testkits.TaskOptions{Config: cfg, Templates: config.Templates{"k8s/vector-values-alicloud.yaml": tmpl}}
			}(),
			wantErr: true,
			errMsg:  "secrets",
		},
		{
			name:  "build succeeds with alicloud vendor when secret exists",
			agent: testkits.NewKubernetesAgentBuilder().Build(),
			opts: func() testkits.TaskOptions {
				cfg := baseVectorConfig()
				cfg.O11yConfig.Vendor = "alicloud"
				secret := &corev1.Secret{
					ObjectMeta: metav1.ObjectMeta{Name: "o11y-oss-secret", Namespace: "observability"},
					Data:       map[string][]byte{"access_key": []byte("test-ak"), "secret_key": []byte("test-sk")},
				}
				return testkits.TaskOptions{Config: cfg, Templates: config.Templates{"k8s/vector-values-alicloud.yaml": tmpl}, LocalObjects: []client.Object{secret}}
			}(),
			outContains: []string{"test-ak", "test-sk"},
		},
		{
			name: "build with custom annotations",
			agent: testkits.NewKubernetesAgentBuilder().
				WithAnnotations(map[string]string{
					consts.AnnotationKeyO11yLogBucketName: "log-bucket-name",
					consts.AnnotationKeyO11yAgentRoleArn:  "arn:aws:iam::123456789:role/agent-role",
					consts.AnnotationKeyO11yDesiredSpec:   "default",
				}).
				Build(),
			opts: func() testkits.TaskOptions {
				cfg := baseVectorConfig()
				cfg.O11yConfig.Region = "us-west-2"
				return testkits.TaskOptions{Config: cfg, Templates: config.Templates{"k8s/vector-values-aws.yaml": tmpl}}
			}(),
			outContains: []string{"region: us-west-2", "bucket: log-bucket-name", "roleARN: arn:aws:iam::123456789:role/agent-role"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			task := makeVectorTask(tt.agent, tt.opts)
			result, err := task.build()
			if tt.wantErr {
				assert.Error(t, err)
				if tt.errMsg != "" {
					assert.Contains(t, err.Error(), tt.errMsg)
				}
				return
			}
			assert.NoError(t, err)
			for _, expected := range tt.outContains {
				assert.Contains(t, result, expected)
			}
			for _, excluded := range tt.outExcludes {
				assert.NotContains(t, result, excluded)
			}
		})
	}
}
