#!/bin/bash

wf-recorder_check() {
	if pgrep -x "wf-recorder" > /dev/null; then
		pkill -INT -x wf-recorder
		pkill -RTMIN+11 waybar
		exit 0
	fi

	record
}

record() {
	pkill -RTMIN+11 waybar

	screencast_dir="$HOME/Screenrecord"
	mkdir -p "$screencast_dir"
	timestamp=$(date +"%Y-%m-%d-%H-%M-%S")
	raw_file="$screencast_dir/screencast_$timestamp.mkv"
	final_file="${raw_file%.*}.mp4"

	# Grabar
	wf-recorder --audio=VirtualSink.monitor -c h264_vaapi -d /dev/dri/by-path/pci-0000:65:00.0-render -f "$raw_file"

	pkill -RTMIN+11 waybar

	# Verificar si el archivo se grabó
	if [ ! -s "$raw_file" ]; then
		notify-send " Grabación fallida: archivo vacío"
		exit 1
	fi

	# Elegir encoder
	if ! gst-inspect-1.0 nvh264enc &>/dev/null; then
		notify-send "️ nvh264enc no disponible, usando x264enc"
		video_encoder="x264enc"
	else
		video_encoder="nvh264enc"
	fi

	# Audio sí o no
	has_audio=$(ffprobe -loglevel error -select_streams a -show_entries stream=codec_type -of csv=p=0 "$raw_file")
	if [ "$has_audio" = "audio" ]; then
		audio_pipeline='d. ! queue ! audioconvert ! fdkaacenc ! queue ! mux.'
	else
		audio_pipeline=""
	fi

	# Pipeline del video
	if [ "$video_encoder" = "nvh264enc" ]; then
		video_encoder_cmd="d. ! queue ! nvh264enc bitrate=1500 ! queue ! mux."
	else
		video_encoder_cmd="d. ! queue ! $video_encoder ! queue ! mux."
	fi

	# Transcodificar
	switcherooctl -g 1 gst-launch-1.0 -v \
		filesrc location="$raw_file" ! decodebin name=d \
		$video_encoder_cmd \
		$audio_pipeline \
		mp4mux name=mux ! filesink location="$final_file"

	# Verificar resultado
	if [ ! -s "$final_file" ]; then
		notify-send " Error al convertir a mp4"
		exit 1
	fi

	notify-send " Grabación procesada"

	# Subir y copiar link
	link=$(~/.local/bin/gitlab-paste "$final_file" | grep -o 'https://gitlab.com/-/snippets/[^ ]*')
	notify-send " Video subido" "Link copiado: $link"

	rm "$raw_file"
}

wf-recorder_check

