package kitty

import (
	
	
	
	
	
	
	

	
)

var (
	// GraphicsTempDir is the directory where temporary files are stored.
	// This is used in [WriteKittyGraphics] along with [os.CreateTemp].
	GraphicsTempDir = ""

	// GraphicsTempPattern is the pattern used to create temporary files.
	// This is used in [WriteKittyGraphics] along with [os.CreateTemp].
	// The Kitty Graphics protocol requires the file path to contain the
	// substring "tty-graphics-protocol".
	GraphicsTempPattern = "tty-graphics-protocol-*"
)

// EncodeGraphics writes an image using the Kitty Graphics protocol with the
// given options to w. It chunks the written data if o.Chunk is true.
//
// You can omit m and use nil when rendering an image from a file. In this
// case, you must provide a file path in o.File and use o.Transmission =
// [File]. You can also use o.Transmission = [TempFile] to write
// the image to a temporary file. In that case, the file path is ignored, and
// the image is written to a temporary file that is automatically deleted by
// the terminal.
//
// See https://sw.kovidgoyal.net/kitty/graphics-protocol/
func ( io.Writer,  image.Image,  *Options) error {
	if  == nil {
		 = &Options{}
	}

	if .Transmission == 0 && len(.File) != 0 {
		.Transmission = File
	}

	var  bytes.Buffer // the data to be encoded into base64
	 := &Encoder{
		Compress: .Compression == Zlib,
		Format:   .Format,
	}

	switch .Transmission {
	case Direct:
		if  := .Encode(&, );  != nil {
			return fmt.Errorf("failed to encode direct image: %w", )
		}

	case SharedMemory:
		//nolint:godox
		// TODO: Implement shared memory
		return fmt.Errorf("shared memory transmission is not yet implemented")

	case File:
		if len(.File) == 0 {
			return ErrMissingFile
		}

		,  := os.Open(.File)
		if  != nil {
			return fmt.Errorf("failed to open file: %w", )
		}

		defer .Close() //nolint:errcheck

		,  := .Stat()
		if  != nil {
			return fmt.Errorf("failed to get file info: %w", )
		}

		 := .Mode()
		if !.IsRegular() {
			return fmt.Errorf("file is not a regular file")
		}

		// Write the file path to the buffer
		if ,  := .WriteString(.Name());  != nil {
			return fmt.Errorf("failed to write file path to buffer: %w", )
		}

	case TempFile:
		,  := os.CreateTemp(GraphicsTempDir, GraphicsTempPattern)
		if  != nil {
			return fmt.Errorf("failed to create file: %w", )
		}

		defer .Close() //nolint:errcheck

		if  := .Encode(, );  != nil {
			return fmt.Errorf("failed to encode image to file: %w", )
		}

		// Write the file path to the buffer
		if ,  := .WriteString(.Name());  != nil {
			return fmt.Errorf("failed to write file path to buffer: %w", )
		}
	}

	// Encode image to base64
	var  bytes.Buffer // the base64 encoded image to be written to w
	 := base64.NewEncoder(base64.StdEncoding, &)
	if ,  := .WriteTo();  != nil {
		return fmt.Errorf("failed to write base64 encoded image to payload: %w", )
	}
	if  := .Close();  != nil {
		return  //nolint:wrapcheck
	}

	// If not chunking, write all at once
	if !.Chunk {
		,  := io.WriteString(, ansi.KittyGraphics(.Bytes(), .Options()...))
		return  //nolint:wrapcheck
	}

	// Write in chunks
	var (
		 error
		   int
	)
	 := make([]byte, MaxChunkSize)
	 := true
	 := .ChunkFormatter
	if  == nil {
		// Default to no formatting
		 = func( string) string { return  }
	}

	for {
		// Stop if we read less than the chunk size [MaxChunkSize].
		,  = io.ReadFull(&, )
		if errors.Is(, io.ErrUnexpectedEOF) || errors.Is(, io.EOF) {
			break
		}
		if  != nil {
			return fmt.Errorf("failed to read chunk: %w", )
		}

		 := buildChunkOptions(, , false)
		if ,  := io.WriteString(,
			(ansi.KittyGraphics([:], ...)));  != nil {
			return  //nolint:wrapcheck
		}

		 = false
	}

	// Write the last chunk
	 := buildChunkOptions(, , true)
	_,  = io.WriteString(, (ansi.KittyGraphics([:], ...)))
	return  //nolint:wrapcheck
}

// buildChunkOptions creates the options slice for a chunk.
func ( *Options, ,  bool) []string {
	var  []string
	if  {
		 = .Options()
	} else {
		// These options are allowed in subsequent chunks
		 := .Quiet
		if .Quite > 0 {
			// handle deprecated Quite field.
			 = .Quite
		}
		if  > 0 {
			 = append(, fmt.Sprintf("q=%d", ))
		}
		if .Action == Frame {
			 = append(, "a=f")
		}
	}

	if ! || ! {
		// We don't need to encode the (m=) option when we only have one chunk.
		if  {
			 = append(, "m=0")
		} else {
			 = append(, "m=1")
		}
	}
	return 
}