#!/bin/bash
# =============================================================
# CLI Refactor Verification Atomicity Test
# =============================================================
# Purpose: Verify all atomicity fixes work correctly
# - Plan artifacts always visible during verification
# - Automatic stash restore on all exit paths (success, failure, signal)
# - No stash conflicts during restore
# - Dry-run safety
# - Reproducible full-run

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
SCRIPT="scripts/cli-refactor-verify.sh"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Test counters
PASS=0
FAIL=0

# Helper functions
log_pass() {
    echo -e "${GREEN}✓ PASS${NC} $1"
    ((PASS++))
}

log_fail() {
    echo -e "${RED}✗ FAIL${NC} $1"
    ((FAIL++))
}

log_section() {
    echo -e "\n${YELLOW}===${NC} $1 ${YELLOW}===${NC}"
}

# Save original state
save_state() {
    echo "Saving original git state..."
    git status --porcelain > /tmp/original_state.txt
    git stash list > /tmp/original_stash.txt
}

# Check state matches original
check_state() {
    echo "Checking git state..."
    local current_state
    current_state=$(git status --porcelain)
    
    if [[ "$current_state" == "$(cat /tmp/original_state.txt)" ]]; then
        log_pass "Git state matches original"
        return 0
    else
        log_fail "Git state differs from original"
        echo "Expected:"
        cat /tmp/original_state.txt
        echo "Got:"
        echo "$current_state"
        return 1
    fi
}

# Check stash is empty
check_stash() {
    echo "Checking stash state..."
    local stash
    stash=$(git stash list)
    
    if [[ -z "$stash" ]]; then
        log_pass "Stash is empty (cleaned up)"
        return 0
    else
        log_fail "Stash exists (not cleaned up)"
        echo "$stash"
        return 1
    fi
}

# =============================================================
# Test 1: Failure Path Auto-Restores
# =============================================================
test_failure_path() {
    log_section "Test 1: Failure path auto-restores"
    
    # Run verification (will fail due to verification errors)
    cd "$PROJECT_ROOT"
    if "$SCRIPT" --check 2>&1 | tail -5; then
        log_fail "Verification should have failed"
        return 1
    fi
    
    # Check state
    check_state || return 1
    check_stash || return 1
    
    log_pass "Failure path test complete"
}

# =============================================================
# Test 2: Plan Artifacts Always Visible
# =============================================================
test_plan_visibility() {
    log_section "Test 2: Plan artifacts remain visible"
    
    # Create temporary modification
    echo "# test" >> "$PROJECT_ROOT/plan.yaml"
    
    # Run verification (will fail)
    cd "$PROJECT_ROOT"
    if "$SCRIPT" --check 2>&1 | tail -5; then
        : # Expected to fail
    fi
    
    # Check plan.yaml is still modified
    if git diff "$PROJECT_ROOT/plan.yaml" | grep -q "# test"; then
        log_pass "Plan artifact visible throughout verification"
        # Clean up
        git checkout -- "$PROJECT_ROOT/plan.yaml"
    else
        log_fail "Plan artifact hidden or lost"
        return 1
    fi
    
    check_stash || return 1
}

# =============================================================
# Test 3: Dry-Run Safety
# =============================================================
test_dry_run() {
    log_section "Test 3: Dry-run safety (no state changes)"
    
    # Run dry-run
    cd "$PROJECT_ROOT"
    if ! "$SCRIPT" --check --dry-run 2>&1 | tail -5; then
        log_fail "Dry-run should succeed"
        return 1
    fi
    
    # Check state unchanged
    check_state || return 1
    check_stash || return 1
    
    log_pass "Dry-run safety test complete"
}

# =============================================================
# Test 4: Reproducible Full-Run
# =============================================================
test_reproducible() {
    log_section "Test 4: Reproducible verification"
    
    cd "$PROJECT_ROOT"
    
    # Run twice to verify both paths work
    if "$SCRIPT" --check 2>&1 | tail -5; then
        : # Expected to fail
    fi
    
    check_state || return 1
    check_stash || return 1
    
    log_pass "Reproducible test complete"
}

# =============================================================
# Run all tests
# =============================================================
main() {
    log_section "Starting Atomicity Tests"
    
    # Save original state
    save_state
    
    # Run tests
    test_failure_path || true
    test_plan_visibility || true
    test_dry_run || true
    test_reproducible || true
    
    # Summary
    log_section "Test Summary"
    echo "Passed: $PASS"
    echo "Failed: $FAIL"
    
    if [[ $FAIL -eq 0 ]]; then
        echo -e "${GREEN}All atomicity tests passed!${NC}"
        exit 0
    else
        echo -e "${RED}Some atomicity tests failed${NC}"
        exit 1
    fi
}

# Run main
main "$@"