package scanner

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/dhowden/tag"
)

type ScannedSong struct {
	Title    string
	Artist   string
	Album    string
	Duration int
	Path     string
}

func ScanDirectory(dirPath string) ([]ScannedSong, error) {
	songs := []ScannedSong{}

	if _, err := os.Stat(dirPath); os.IsNotExist(err) {
		return songs, err
	}
	filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {

		if info.IsDir() {
			return nil
		}

		if !isAudioFile(path) {
			return nil
		}

		if song, err := processAudioFile(path); err != nil {
			return err
		} else {
			songs = append(songs, song)
		}
		return nil
	})

	return songs, nil
}

func processAudioFile(filePath string) (ScannedSong, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return ScannedSong{}, fmt.Errorf("failed to open file: %v", err)
	}
	defer file.Close()

	metadata, err := tag.ReadFrom(file)
	if err != nil {
		return ScannedSong{}, fmt.Errorf("failed to read metadata: %v", err)
	}

	title := metadata.Title()
	if title == "" {
		title = filepath.Base(filePath)
	}

	artist := metadata.Artist()
	if artist == "" {
		artist = "Unknown Artist"
	}

	album := metadata.Album()
	if album == "" {
		album = "Unknown Album"
	}

	return ScannedSong{
		Title:    title,
		Artist:   artist,
		Album:    album,
		Duration: 100,
		Path:     filePath,
	}, nil
}

func isAudioFile(path string) bool {
	ext := strings.ToLower(filepath.Ext(path))
	audioExtensions := []string{".mp3", ".flac", ".m4a", ".wav", ".ogg"}

	for _, audioExt := range audioExtensions {
		if ext == audioExt {
			return true
		}
	}
	return false
}
