package main

import (
	"bytes"
	_ "embed"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/faiface/beep/mp3"
	"github.com/faiface/beep/speaker"
	"github.com/fatih/color"
)

//go:embed blessing.txt
var blessingBytes []byte

//go:embed chant.mp3
var chantBytes []byte

func playChant() {
	streamer, format, err := mp3.Decode(io.NopCloser(bytes.NewReader(chantBytes)))
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: Unable to decode chant: %v\n", err)
		return
	}
	speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
	speaker.Play(streamer)
}

func main() {
	blessing := string(blessingBytes)

	go playChant()

	clearScreen := "\033[2J"
	moveCursorTop := "\033[H"
	fmt.Print(clearScreen + moveCursorTop)

	// Resize the terminal (Windows example)
	resizeTerminal(50, 42) // Width, Height

	// ANSI-compatible colors using "fatih/color"
	boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
	italicRed := color.New(color.FgRed, color.Italic).SprintFunc()

	// Terminal width (you can adjust this to your needs)
	width := 50 // 50% thinner width

	// Header and Footer
	header := "+++ INITIATE COGITATOR RITE +++"
	footer := "<< SYSTEM: BLESSED BY THE OMNISSIAH >>"

	// Print header, center-aligned
	fmt.Println(boldGreen(centerText(header, width)))

	// Print the blessing with a slight delay between lines
	lines := strings.Split(blessing, "\n")
	for _, line := range lines {
		fmt.Println(centerText(line, width))
		time.Sleep(30 * time.Millisecond) // tweak for effect
	}

	// Print footer, center-aligned and italicized
	fmt.Print("\n")
	fmt.Print(italicRed(centerText(footer, width)))

	select {} // keep app running while audio plays
}

// Resize the terminal window (Windows-specific)
func resizeTerminal(cols, rows int) {
	cmd := exec.Command("mode", fmt.Sprintf("%d,%d", cols, rows))
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		fmt.Printf("Error resizing terminal: %v\n", err)
	}
}

// Function to center text based on terminal width
func centerText(text string, width int) string {
	padding := (width - len(text)) / 2
	if padding < 0 {
		padding = 0
	}
	return strings.Repeat(" ", padding) + text
}
