package inbox

import (
	"strings"

	"ai-workflow-skill/internal/protocol"
	"ai-workflow-skill/internal/store"

	"github.com/spf13/cobra"
)

type artifactOptions struct {
	paths         []string
	kinds         []string
	metadataJSONs []string
}

func addArtifactFlags(cmd *cobra.Command, opts *artifactOptions) {
	cmd.Flags().StringArrayVar(&opts.paths, "artifact", nil, "Artifact path to attach; may be repeated")
	cmd.Flags().StringArrayVar(&opts.kinds, "artifact-kind", nil, "Artifact kind; one value applies to all, or match artifact count")
	cmd.Flags().StringArrayVar(&opts.metadataJSONs, "artifact-metadata-json", nil, "Artifact metadata JSON; one value applies to all, or match artifact count")
}

func resolveArtifacts(opts artifactOptions) ([]store.ArtifactInput, error) {
	if len(opts.paths) == 0 {
		if len(opts.kinds) > 0 || len(opts.metadataJSONs) > 0 {
			return nil, protocol.InvalidInput("artifact-kind and artifact-metadata-json require at least one artifact path", nil)
		}
		return nil, nil
	}

	kinds, err := expandArtifactValues(opts.kinds, len(opts.paths), "artifact-kind")
	if err != nil {
		return nil, err
	}
	metadataJSONs, err := expandArtifactValues(opts.metadataJSONs, len(opts.paths), "artifact-metadata-json")
	if err != nil {
		return nil, err
	}

	artifacts := make([]store.ArtifactInput, 0, len(opts.paths))
	for i, path := range opts.paths {
		if strings.TrimSpace(path) == "" {
			return nil, protocol.InvalidInput("artifact path cannot be empty", nil)
		}

		artifact := store.ArtifactInput{
			Path: path,
			Kind: "file",
		}
		if len(kinds) > 0 {
			artifact.Kind = kinds[i]
		}
		if len(metadataJSONs) > 0 {
			artifact.MetadataJSON = metadataJSONs[i]
		}
		artifacts = append(artifacts, artifact)
	}

	return artifacts, nil
}

func expandArtifactValues(values []string, target int, flagName string) ([]string, error) {
	switch len(values) {
	case 0:
		return nil, nil
	case 1:
		out := make([]string, target)
		for i := range out {
			out[i] = values[0]
		}
		return out, nil
	case target:
		return values, nil
	default:
		return nil, protocol.InvalidInput(flagName+" must be specified once or once per artifact", nil)
	}
}
