package cmd

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"time"

	"github.com/pkg/errors"
	"github.com/snyk/driftctl/pkg/analyser"
	"github.com/spf13/cobra"
)

func NewGenDriftIgnoreCmd() *cobra.Command {
	opts := &analyser.GenDriftIgnoreOptions{}

	cmd := &cobra.Command{
		Use:   "gen-driftignore",
		Short: "Generate a .driftignore file based on your scan result",
		Long:  "This command will generate a new .driftignore file containing your current drifts\n\nExample: driftctl scan -o json://stdout | driftctl gen-driftignore",
		Args:  cobra.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			_, list, err := genDriftIgnore(opts)
			if err != nil {
				return err
			}

			ignoreFile := os.Stdout
			if opts.OutputPath != "-" {
				var err error
				ignoreFile, err = os.OpenFile(opts.OutputPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
				if err != nil {
					return errors.Errorf("error opening output file: %s", err)
				}
				defer ignoreFile.Close()
				fmt.Fprintf(os.Stderr, "Appending ignore rules to %s\n", opts.OutputPath)
			}
			fmt.Fprintf(ignoreFile, "# Generated by gen-driftignore cmd @ %s\n%s\n", time.Now().Format(time.RFC1123), list)

			return nil
		},
	}

	fl := cmd.Flags()

	fl.BoolVar(&opts.ExcludeUnmanaged, "exclude-unmanaged", false, "Exclude resources not managed by IaC")
	fl.BoolVar(&opts.ExcludeDeleted, "exclude-missing", false, "Exclude missing resources")
	fl.BoolVar(&opts.ExcludeDrifted, "exclude-changed", false, "Exclude resources that changed on cloud provider")
	fl.StringVarP(&opts.InputPath, "input", "i", "-", "Input where the JSON should be parsed from. Defaults to stdin.")
	fl.StringVarP(&opts.OutputPath, "output", "o", ".driftignore", "Output file path to write the driftignore to.")

	return cmd
}

func genDriftIgnore(opts *analyser.GenDriftIgnoreOptions) (int, string, error) {
	driftFile := os.Stdin
	if opts.InputPath != "-" {
		var err error
		driftFile, err = os.Open(opts.InputPath)
		if err != nil {
			return 0, "", err
		}
		defer driftFile.Close()
	}

	input, err := io.ReadAll(driftFile)
	if err != nil {
		return 0, "", err
	}

	analysis := &analyser.Analysis{}
	err = json.Unmarshal(input, analysis)
	if err != nil {
		return 0, "", err
	}

	n, list := analysis.DriftIgnoreList(*opts)

	return n, list, nil
}
