#!/bin/bash

cd /Volumes/Scratch/Sites/CMassP2

# Read registry and process
completed=0

# Extract all lines with status "i"
grep '| .* | .* | .* | i | ' .smbatcher/REGISTRY.md | while read line; do
    # Parse the line
    domain=$(echo "$line" | awk -F'|' '{print $2}' | xargs)

    # Check if site directory exists with all required files
    site_dir="sites/${domain}-v1"

    if [ -d "$site_dir" ] && [ -f "$site_dir/index.html" ] && [ -f "$site_dir/styles.css" ] && [ -f "$site_dir/script.js" ]; then
        # All files exist - mark as complete
        iso_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S")
        echo "COMPLETE: $domain"
        ((completed++))

        # Update the registry line: replace status "i" with "I" and update timestamp
        sed -i '' "s/| $domain | \(.*\) | i | 001 | .* |/| $domain | \1 | I | 001 | $iso_timestamp |/" .smbatcher/REGISTRY.md
    fi
done

# Re-read and count completed sites (since the above loop runs in a subshell)
# We'll do this more carefully by recreating the registry

# Count "i" status entries
i_count=$(grep -c '| .* | .* | .* | i | ' .smbatcher/REGISTRY.md)
echo "Initially found $i_count sites with status 'i'"

# Process each one
completed_count=0
temp_registry=$(mktemp)

while IFS= read -r line; do
    if [[ "$line" =~ "^| ".*" | ".*" | ".*" | i | " ]]; then
        # Extract domain
        domain=$(echo "$line" | awk -F'|' '{print $2}' | xargs)
        title=$(echo "$line" | awk -F'|' '{print $3}' | xargs)
        description=$(echo "$line" | awk -F'|' '{print $4}' | xargs)
        batch=$(echo "$line" | awk -F'|' '{print $5}' | xargs)

        site_dir="sites/${domain}-v1"

        if [ -d "$site_dir" ] && [ -f "$site_dir/index.html" ] && [ -f "$site_dir/styles.css" ] && [ -f "$site_dir/script.js" ]; then
            # All files exist
            iso_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S")
            echo "COMPLETE: $domain"
            new_line="| $domain | $title | $description | I | $batch | $iso_timestamp |"
            echo "$new_line" >> "$temp_registry"
            ((completed_count++))
        else
            # Keep as is
            echo "$line" >> "$temp_registry"
        fi
    else
        # Keep non-data lines as is
        echo "$line" >> "$temp_registry"
    fi
done < .smbatcher/REGISTRY.md

# Replace original with updated
mv "$temp_registry" .smbatcher/REGISTRY.md

echo ""
echo "========================================="
echo "Marked $completed_count sites as complete (status 'I')"
echo "========================================="
