#!/bin/bash

set -euo pipefail

PID_FILE="/tmp/blurt.pid"
AUDIO_FILE="/tmp/blurt.wav"
API_URL="https://api.openai.com/v1/audio/transcriptions"

notify() {
    notify-send "blurt" "$1"
}

get_api_key() {
    keyring get openai-api-key felixm 2>/dev/null || {
        notify "Error: Could not get API key from keyring"
        exit 1
    }
}

start_recording() {
    notify "Recording..."
    pw-record --format=s16 --rate=16000 --channels=1 "$AUDIO_FILE" &
    echo $! > "$PID_FILE"
}

stop_recording() {
    local pid="$1"
    kill -INT "$pid" 2>/dev/null || true
    wait "$pid" 2>/dev/null || true
    rm -f "$PID_FILE"
}

transcribe() {
    notify "Transcribing..."

    local api_key
    api_key=$(get_api_key)

    local response
    response=$(curl -s -X POST "$API_URL" \
        -H "Authorization: Bearer $api_key" \
        -F "file=@$AUDIO_FILE" \
        -F "model=whisper-1")

    local text
    text=$(echo "$response" | jq -r '.text // empty')

    if [[ -z "$text" ]]; then
        local error
        error=$(echo "$response" | jq -r '.error.message // "Unknown error"')
        notify "Error: $error"
        exit 1
    fi

    echo -n "$text" | xclip -selection clipboard

    # If active window is kitty, insert text directly
    local window_class
    window_class=$(xdotool getactivewindow getwindowclassname 2>/dev/null || echo "")
    if [[ "$window_class" == *"kitty"* ]]; then
        xdotool type --clearmodifiers -- "$text"
    fi

    local preview="${text:0:50}"
    [[ ${#text} -gt 50 ]] && preview="${preview}..."
    notify "Copied: $preview"
}

main() {
    if [[ -f "$PID_FILE" ]]; then
        local pid
        pid=$(cat "$PID_FILE")

        if kill -0 "$pid" 2>/dev/null; then
            stop_recording "$pid"
            transcribe
        else
            rm -f "$PID_FILE"
            start_recording
        fi
    else
        start_recording
    fi
}

main
