package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

// Function to download a file from a URL and save it locally
func downloadFile(url string, fileName string) error {
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create(fileName)
	if err != nil {
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return err
}

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ./downloadcast <hastebin-url>")
		os.Exit(1)
	}

	hastebinURL := os.Args[1]
	if !strings.HasPrefix(hastebinURL, "https://haste.nixc.us/") {
		fmt.Println("Invalid Hastebin URL. Please provide a valid URL from haste.nixc.us")
		os.Exit(1)
	}

	// Get the key from the URL
	parts := strings.Split(hastebinURL, "/")
	if len(parts) < 4 {
		fmt.Println("Invalid Hastebin URL format")
		os.Exit(1)
	}
	key := parts[len(parts)-1]

	// Build the raw URL for downloading the content
	rawURL := fmt.Sprintf("https://haste.nixc.us/raw/%s", key)
	fileName := fmt.Sprintf("%s.cast", key)

	fmt.Printf("Downloading from %s to %s\n", rawURL, fileName)

	// Download the file
	err := downloadFile(rawURL, fileName)
	if err != nil {
		fmt.Printf("Error downloading the file: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Downloaded file saved as %s\n", fileName)

	// Optional: Play the downloaded cast file using asciinema
	playCmd := exec.Command("asciinema", "play", fileName)
	playCmd.Stdout = os.Stdout
	playCmd.Stderr = os.Stderr
	err = playCmd.Run()
	if err != nil {
		fmt.Printf("Error playing the cast file: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("Playback finished.")
}
