#!/bin/bash
# YAML Formatter for Home Assistant Configuration
# Only formats YAML files that were created/modified by Claude during the current session
# Formats YAML files to match yamllint configuration:
# - 2 spaces indentation
# - Standard sequence indentation (indent-sequences: true)
# - Preserves Home Assistant specific tags (!include, !secret, !input)

# Check if file is a YAML file
file="$1"
if [[ ! "$file" =~ \.(yaml|yml)$ ]]; then
    exit 0
fi

# Check if file has Claude header comment (indicating it was generated by Claude)
if ! head -3 "$file" 2>/dev/null | grep -q "# Generated by Claude - Home Assistant Configuration, https://github.com/philippb/claude-homeassistant"; then
    echo "Skipped YAML formatting (not generated by Claude): $file"
    exit 0
fi

# Skip secrets files and hidden files
if [[ "$file" =~ secrets\.yaml || "$file" =~ /\. ]]; then
    exit 0
fi

# Handle empty files - leave them empty (no newline needed)
if [ ! -s "$file" ]; then
    echo "Skipped empty YAML: $file"
    exit 0
fi

# Create a temporary file
temp_file=$(mktemp)

# Use yq to format the YAML file with 2-space indentation
# The -I 2 flag sets 2-space indentation
yq eval '.' -I 2 "$file" > "$temp_file" 2>/dev/null

# Check if yq succeeded and the file is not empty
if [ $? -eq 0 ] && [ -s "$temp_file" ]; then
    # Ensure the file ends with exactly one newline (required by end-of-file-fixer)
    # Remove any trailing whitespace and ensure single trailing newline
    sed -e :a -e '/^\s*$/N;ba' -e 's/\n*$//' "$temp_file" > "${temp_file}.clean"
    echo >> "${temp_file}.clean"  # Add exactly one newline at the end

    # Replace the original file with the formatted version
    mv "${temp_file}.clean" "$file"
    rm -f "$temp_file"
    echo "Formatted YAML: $file"
else
    # If yq failed (probably due to HA-specific tags), clean up temp file
    rm -f "$temp_file"
    echo "Skipped YAML formatting (contains HA-specific tags): $file"
fi
