#!/usr/bin/env bash
# Nomarchy State Migration Script
# Migrates state from old locations to unified ~/.config/nomarchy/state.json

set -e

NEW_STATE_DIR="$HOME/.config/nomarchy"
NEW_STATE_FILE="$NEW_STATE_DIR/state.json"
OLD_HOME_STATE="$HOME/.config/home-manager/state.json"
OLD_SYSTEM_STATE="/etc/nixos/state.json"

mkdir -p "$NEW_STATE_DIR"

# Initialize new state file if it doesn't exist
if [[ ! -f "$NEW_STATE_FILE" ]]; then
    echo "{}" > "$NEW_STATE_FILE"
fi

# Function to safely merge JSON
merge_json() {
    local source="$1"
    if [[ -f "$source" ]]; then
        echo "Migrating from $source..."
        TMP_FILE=$(mktemp)
        # Merge source into new state (new state values take precedence if conflict)
        jq -s '.[0] * .[1]' "$source" "$NEW_STATE_FILE" > "$TMP_FILE" && mv "$TMP_FILE" "$NEW_STATE_FILE"
    fi
}

# Migrate old home-manager state
if [[ -f "$OLD_HOME_STATE" ]] && [[ "$OLD_HOME_STATE" != "$NEW_STATE_FILE" ]]; then
    merge_json "$OLD_HOME_STATE"
    echo "Old home state migrated. You can remove: $OLD_HOME_STATE"
fi

# Check if system state exists and user wants to sync it
if [[ -f "$OLD_SYSTEM_STATE" ]]; then
    echo ""
    echo "System state found at $OLD_SYSTEM_STATE"
    echo "Note: System state will continue to be read from /etc/nixos/state.json"
    echo "      for system-level NixOS configuration."
fi

# Run the preflight migration for any legacy formats
if command -v nomarchy-preflight-migration &> /dev/null; then
    nomarchy-preflight-migration
fi

echo ""
echo "Migration complete!"
echo "New state location: $NEW_STATE_FILE"
echo ""
echo "Current state:"
jq '.' "$NEW_STATE_FILE"
