package lifecycle

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// Kept from the deleted Tiltfile generator. The source-build helpers below are
// used by materialize_steps.go; writeJSONFile is used by session_context_write_step.go
// and writeTextFile only backs it. None of them concern Tiltfile generation, which
// is why they outlived it.

// sourceServiceNeedsAWSIAMAuthenticatorRuntimeToolchain reports whether a
// source-built service talks to EKS at runtime and therefore needs
// aws-iam-authenticator on its image.
func sourceServiceNeedsAWSIAMAuthenticatorRuntimeToolchain(serviceName string) bool {
	switch strings.TrimSpace(serviceName) {
	case "dataplane-manager", "regional-server":
		return true
	default:
		return false
	}
}

// appendAWSIAMAuthenticatorRuntimeToolchain adds the aws-iam-authenticator
// install to a Dockerfile being built for a source service.
func appendAWSIAMAuthenticatorRuntimeToolchain(b *strings.Builder) {
	b.WriteString("ARG TARGETARCH\n")
	b.WriteString("ARG AWS_IAM_AUTHENTICATOR_VERSION=0.7.8\n")
	b.WriteString("RUN apk add --no-cache ca-certificates wget && \\\n")
	b.WriteString("    wget -O /usr/local/bin/aws-iam-authenticator ")
	b.WriteString("\"https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/")
	b.WriteString("v${AWS_IAM_AUTHENTICATOR_VERSION}/")
	b.WriteString("aws-iam-authenticator_${AWS_IAM_AUTHENTICATOR_VERSION}_linux_${TARGETARCH:-amd64}\" && \\\n")
	b.WriteString("    chmod +x /usr/local/bin/aws-iam-authenticator\n")
}

func writeTextFile(path, content string) error {
	cleanPath := filepath.Clean(path)
	if err := os.MkdirAll(filepath.Dir(cleanPath), 0o755); err != nil {
		return fmt.Errorf("create file dir: %w", err)
	}
	return os.WriteFile(cleanPath, []byte(content), 0o600)
}

func writeJSONFile(path string, value any) error {
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return fmt.Errorf("create json dir: %w", err)
	}
	data, err := json.MarshalIndent(value, "", "  ")
	if err != nil {
		return fmt.Errorf("marshal json: %w", err)
	}
	return writeTextFile(path, string(data))
}
