package wav

import (
	"fmt"
	"os"

	"github.com/go-audio/audio"
	"github.com/go-audio/wav"
)

// WriteWAVFileWithOptions writes float64 audio data to a WAV file with specified sample rate and bit depth
func WriteWAVFileWithOptions(filePath string, data []float64, sampleRate, bitDepth int) error {
	file, err := os.Create(filePath)
	if err != nil {
		return fmt.Errorf("failed to create file %s: %w", filePath, err)
	}
	defer file.Close()

	// Convert float64 to appropriate integer format based on bit depth
	var intData []int
	switch bitDepth {
	case 16:
		intData = make([]int, len(data))
		for i, sample := range data {
			// Clamp to [-1, 1] range
			if sample > 1.0 {
				sample = 1.0
			} else if sample < -1.0 {
				sample = -1.0
			}
			// Convert to 16-bit integer
			intSample := int(sample * float64(1<<15))
			intData[i] = intSample
		}
	case 24:
		intData = make([]int, len(data))
		for i, sample := range data {
			// Clamp to [-1, 1] range
			if sample > 1.0 {
				sample = 1.0
			} else if sample < -1.0 {
				sample = -1.0
			}
			// Convert to 24-bit integer
			intSample := int(sample * float64(1<<23))
			intData[i] = intSample
		}
	case 32:
		intData = make([]int, len(data))
		for i, sample := range data {
			// Clamp to [-1, 1] range
			if sample > 1.0 {
				sample = 1.0
			} else if sample < -1.0 {
				sample = -1.0
			}
			// Convert to 32-bit integer
			intSample := int(sample * float64(1<<31))
			intData[i] = intSample
		}
	default:
		return fmt.Errorf("unsupported bit depth: %d", bitDepth)
	}

	// Create audio buffer
	audioBuf := &audio.IntBuffer{
		Format: &audio.Format{
			NumChannels: 1,
			SampleRate:  sampleRate,
		},
		Data:           intData,
		SourceBitDepth: bitDepth,
	}

	// Create WAV encoder
	encoder := wav.NewEncoder(file, sampleRate, bitDepth, 1, 1)
	defer encoder.Close()

	// Write audio data
	if err := encoder.Write(audioBuf); err != nil {
		return fmt.Errorf("failed to write audio data: %w", err)
	}

	return nil
}

// WriteWAVFile writes float64 audio data to a 96kHz 24-bit WAV file (default format)
func WriteWAVFile(filePath string, data []float64, sampleRate int) error {
	return WriteWAVFileWithOptions(filePath, data, sampleRate, 24)
}
