package maker

import (
	"context"
	"os"
	"os/exec"
	"path/filepath"

	"gitea.loveuer.com/yizhisec/pkg3/logger"
	"github.com/samber/lo"
	"yizhisec.com/hsv2/forge/internal/opt"
)

type imageOpt struct {
	Fallbacks     []string
	IgnoreFailure bool
	ForcePull     bool
	Save          string
}

type ImageOpt func(*imageOpt)

func WithImageFallback(fallbacks ...string) ImageOpt {
	return func(o *imageOpt) {
		o.Fallbacks = lo.Filter(fallbacks, func(item string, _ int) bool { return item != "" })
	}
}

func WithImageSave(filename string) ImageOpt {
	return func(o *imageOpt) {
		o.Save = filename
	}
}

func WithImageForcePull() ImageOpt {
	return func(o *imageOpt) {
		o.ForcePull = true
	}
}

func (m *maker) Image(ctx context.Context, name string, opts ...ImageOpt) error {
	var (
		err  error
		o    = &imageOpt{}
		_cmd *exec.Cmd
	)

	for _, fn := range opts {
		fn(o)
	}

	logger.Debug("📋 maker.Image: name = %s, opt = %#v", name, o)

	if !o.ForcePull {
		_cmd = exec.CommandContext(ctx, "docker", "image", "inspect", name)
		if err = _cmd.Run(); err == nil {
			logger.Debug("💿 镜像 %s 已存在", name)
			goto SAVE
		}
	}

	_cmd = exec.CommandContext(ctx, "docker", "pull", name)
	if err = _cmd.Run(); err != nil {
		logger.Debug("❌ 获取原始镜像 %s 失败： %v", name, err)
	} else {
		logger.Debug("✅ 成功获取镜像: %s", name)
		goto SAVE
	}

	for _, fallback := range o.Fallbacks {
		logger.Debug("☑️ 开始获取镜像: %s (%s)", name, fallback)
		_cmd := exec.CommandContext(ctx, "docker", "pull", fallback)
		if err = _cmd.Run(); err != nil {
			logger.Debug("❌ 获取镜像 %s (%s) 失败: %v", name, fallback, err)
			continue
		}

		// pull success, retag image
		_cmd = exec.CommandContext(ctx, "docker", "tag", fallback, name)
		if err = _cmd.Run(); err != nil {
			logger.Debug("❌ 重命名镜像 %s => %s 失败: %s", fallback, name, err)
			continue
		}

		logger.Debug("✅ 成功获取镜像: %s (%s)", name, fallback)
		break
	}

SAVE:
	if o.Save != "" {
		logger.Debug("☑️ 保存镜像 %s 到 %s", name, o.Save)

		_ = os.MkdirAll(filepath.Dir(o.Save), 0755)

		if err = exec.CommandContext(ctx, "docker", "save", "-o", o.Save, name).Run(); err != nil {
			logger.Debug("❌ 保存镜像 %s 到 %s 失败: %v", name, o.Save, err)
		} else {
			logger.Debug("✅ 镜像 %s 保存到 %s 成功", name, o.Save)
		}
	}

	if o.IgnoreFailure {
		return nil
	}

	return err
}

func (m *maker) Images(ctx context.Context) error {
	type Images struct {
		Name     string
		Fallback string
		Save     string
		Force    bool
	}

	var images = []*Images{
		{Name: "quay.io/k0sproject/apiserver-network-proxy-agent:v0.32.0", Fallback: "hub.yizhisec.com/external/apiserver-network-proxy-agent:v0.32.0", Save: "k0s.apiserver-network-proxy-agent.tar"},
		{Name: "quay.io/k0sproject/cni-node:1.7.1-k0s.0", Fallback: "", Save: "k0s.cni-node.tar"},
		{Name: "quay.io/k0sproject/coredns:1.12.2", Fallback: "", Save: "k0s.coredns.tar"},
		{Name: "quay.io/k0sproject/kube-proxy:v1.33.4", Fallback: "", Save: "k0s.kube-proxy.tar"},
		{Name: "quay.io/k0sproject/kube-router:v2.5.0-iptables1.8.11-0", Fallback: "", Save: "k0s.kube-router.tar"},
		{Name: "quay.io/k0sproject/metrics-server:v0.7.2-0", Fallback: "", Save: "k0s.metrics-server.tar"},
		{Name: "quay.io/k0sproject/pause:3.10.1", Fallback: "", Save: "k0s.pause.tar"},

		{Name: "ghcr.io/flannel-io/flannel:v0.27.4", Fallback: "swr.cn-north-4.myhuaweicloud.com/ddn-k8s/ghcr.io/flannel-io/flannel:v0.27.4", Save: "flannel.tar"},
		{Name: "ghcr.io/flannel-io/flannel-cni-plugin:v1.8.0-flannel1", Fallback: "swr.cn-north-4.myhuaweicloud.com/ddn-k8s/ghcr.io/flannel-io/flannel-cni-plugin:v1.8.0-flannel1", Save: "flannel-cni-plugin.tar"},

		{Name: "docker.io/longhornio/longhorn-engine:v1.10.0", Fallback: "docker-mirror.yizhisec.com/longhornio/longhorn-engine:v1.10.0", Save: "longhorn.longhorn-engine.tar"},
		{Name: "docker.io/longhornio/longhorn-manager:v1.10.0", Fallback: "docker-mirror.yizhisec.com/longhornio/longhorn-manager:v1.10.0", Save: "longhorn.longhorn-manager.tar"},
		{Name: "docker.io/longhornio/longhorn-instance-manager:v1.10.0", Fallback: "docker-mirror.yizhisec.com/longhornio/longhorn-instance-manager:v1.10.0", Save: "longhorn.longhorn-instance-manager.tar"},
		{Name: "docker.io/longhornio/longhorn-share-manager:v1.10.0", Fallback: "docker-mirror.yizhisec.com/longhornio/longhorn-share-manager:v1.10.0", Save: "longhorn.longhorn-share-manager.tar"},
		{Name: "docker.io/longhornio/longhorn-ui:v1.10.0", Fallback: "docker-mirror.yizhisec.com/longhornio/longhorn-ui:v1.10.0", Save: "longhorn.longhorn-ui.tar"},
		{Name: "docker.io/longhornio/csi-snapshotter:v8.3.0-20250826", Fallback: "docker-mirror.yizhisec.com/longhornio/csi-snapshotter:v8.3.0-20250826", Save: "longhorn.csi-snapshotter.tar"},
		{Name: "docker.io/longhornio/csi-resizer:v1.14.0-20250826", Fallback: "docker-mirror.yizhisec.com/longhornio/csi-resizer:v1.14.0-20250826", Save: "longhorn.csi-resizer.tar"},
		{Name: "docker.io/longhornio/csi-provisioner:v5.3.0-20250826", Fallback: "docker-mirror.yizhisec.com/longhornio/csi-provisioner:v5.3.0-20250826", Save: "longhorn.csi-provisioner.tar"},
		{Name: "docker.io/longhornio/livenessprobe:v2.16.0-20250826", Fallback: "docker-mirror.yizhisec.com/longhornio/livenessprobe:v2.16.0-20250826", Save: "longhorn.livenessprobe.tar"},
		{Name: "docker.io/longhornio/csi-node-driver-registrar:v2.14.0-20250826", Fallback: "docker-mirror.yizhisec.com/longhornio/csi-node-driver-registrar:v2.14.0-20250826", Save: "longhorn.csi-node-driver-registrar.tar"},
		{Name: "docker.io/longhornio/csi-attacher:v4.9.0-20250826", Fallback: "docker-mirror.yizhisec.com/longhornio/csi-attacher:v4.9.0-20250826", Save: "longhorn.csi-attacher.tar"},

		{Name: "hub.yizhisec.com/external/alpine:3.22.2", Fallback: "", Save: "alpine.tar", Force: true},
		{Name: "hub.yizhisec.com/external/nginx:1.29.1-alpine3.22", Fallback: "", Save: "nginx.1.29.1-alpine3.22.tar"},

		{Name: "docker.io/bitpoke/mysql-operator:v0.6.3", Fallback: "docker-mirror.yizhisec.com/bitpoke/mysql-operator:v0.6.3", Save: "bitpoke.mysql-operator.v0.6.3.tar"},
		{Name: "docker.io/bitpoke/mysql-operator-orchestrator:v0.6.3", Fallback: "docker-mirror.yizhisec.com/bitpoke/mysql-operator-orchestrator:v0.6.3", Save: "bitpoke.mysql-operator-orchestrator.v0.6.3.tar"},
		{Name: "docker.io/bitpoke/mysql-operator-sidecar-8.0:v0.6.3", Fallback: "docker-mirror.yizhisec.com/bitpoke/mysql-operator-sidecar-8.0:v0.6.3", Save: "bitpoke.mysql-operator-sidecar-8.0.v0.6.3.tar"},
		{Name: "docker.io/library/percona:8.0.28-20", Fallback: "docker-mirror.yizhisec.com/library/percona:8.0.28-20", Save: "percona.8.0.28-20.tar"},
		{Name: "docker.io/prom/mysqld-exporter:v0.13.0", Fallback: "docker-mirror.yizhisec.com/prom/mysqld-exporter:v0.13.0", Save: "prom.mysqld-exporter.v0.13.0.tar"},

		{Name: "docker.io/bitnami/redis:8.2.2", Fallback: "hub.yizhisec.com/external/bitnami/redis:8.2.2", Save: "bitnami.redis.8.2.2.tar"},
		{Name: "hub.yizhisec.com/external/elasticsearch:7.17.28", Fallback: "", Save: "elasticsearch.7.17.28.tar"},
		{Name: "hub.yizhisec.com/external/kibana:7.17.28", Fallback: "", Save: "kibana.7.17.28.tar"},
		{Name: "hub.yizhisec.com/external/emqx:5.1", Fallback: "", Save: "emqx.5.1.tar"},

		{Name: "hub.yizhisec.com/build/hybirdscope/front/admin:latest", Fallback: "", Save: "app.front.admin.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/v2/front-user:latest", Fallback: "", Save: "app.front.user.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/user_management:latest", Fallback: "", Save: "app.user.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/gateway_controller:latest", Fallback: "", Save: "app.gateway.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/client_server:latest", Fallback: "", Save: "app.client.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/mie-server:latest", Fallback: "", Save: "app.mie.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/less_dns_service:latest", Fallback: "", Save: "app.less_dns.tar", Force: true},
		{Name: "hub.yizhisec.com/hybridscope/hsnet:release_2.1.0-std", Fallback: "", Save: "app.hsnet.tar", Force: true},
	}

	for _, image := range images {
		image.Save = filepath.Join(opt.Cfg.Make.Dir, "dependency", "image", image.Save)
	}

	logger.Info("☑️ 开始获取镜像(s)...")

	for _, image := range images {

		opts := []ImageOpt{
			WithImageFallback(image.Fallback),
			WithImageSave(image.Save),
		}

		if image.Force {
			opts = append(opts, WithImageForcePull())
		}

		logger.Info("☑️ 获取镜像: %s", image.Name)

		if err := m.Image(ctx, image.Name, opts...); err != nil {
			logger.Error("❌ 获取镜像失败: %s, 可以手动获取后重试", image.Name)
			logger.Debug("❌ 获取镜像失败: %s, %v", image.Name, err)
			return err
		}

		logger.Info("✅ 获取镜像成功: %s", image.Name)
	}

	logger.Info("✅ 获取镜像(s)成功!!!")

	return nil
}
