#!/usr/bin/env bash
# Reunification Workflow Example
# Demonstrates conflict detection and reunification for completed child tasks

set -euo pipefail

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

echo -e "${BLUE}=== Cleave Reunification Workflow ===${NC}\n"

# Assume workspace exists at .cleave/
WORKSPACE=".cleave"

if [ ! -d "$WORKSPACE" ]; then
    echo -e "${RED}Error: Workspace not found at $WORKSPACE${NC}"
    echo "Run 'cleave init' first to create a workspace"
    exit 1
fi

echo -e "${GREEN}Step 1: Validate workspace${NC}"
echo "Ensure all child task files are present and complete"
echo ""

cleave validate --workspace "$WORKSPACE"

echo -e "\n${GREEN}Step 2: Detect conflicts${NC}"
echo "Check for file overlaps, decision contradictions, interface mismatches"
echo ""

# Collect all task result files
TASK_FILES=$(find "$WORKSPACE" -name '*-task.md' -type f | paste -sd, -)

cleave conflicts --results "$TASK_FILES"

echo -e "\n${GREEN}Step 3: Reunify${NC}"
echo "Merge child results and generate merge.md + review.md"
echo ""

cleave reunify --workspace "$WORKSPACE"

echo -e "\n${GREEN}Step 4: Review reunification artifacts${NC}"
echo ""

if [ -f "$WORKSPACE/merge.md" ]; then
    echo -e "${YELLOW}Merge Report:${NC}"
    echo "File: $WORKSPACE/merge.md"
    echo "Contains conflict resolution and merge decisions"
    echo ""
fi

if [ -f "$WORKSPACE/review.md" ]; then
    echo -e "${YELLOW}Adversarial Review:${NC}"
    echo "File: $WORKSPACE/review.md"
    echo "Contains validation checks and integration probes"
    echo ""
fi

echo -e "\n${GREEN}Step 5: Verify merged result${NC}"
echo "Run integration tests and validation commands from review.md"
echo ""

# Example: Run tests mentioned in review.md
if [ -f "$WORKSPACE/review.md" ]; then
    echo "Commands to run (extract from review.md):"
    grep -A 5 "Verification Commands" "$WORKSPACE/review.md" || echo "No verification commands found"
fi

echo ""
echo -e "${BLUE}=== Reunification Complete ===${NC}"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Review $WORKSPACE/merge.md for conflict resolution"
echo "2. Review $WORKSPACE/review.md for validation checks"
echo "3. Run verification commands to ensure integration"
echo "4. Record metrics with 'cleave metrics --workspace $WORKSPACE'"
