#!/usr/bin/env bash
# Metrics Analysis Example
# Demonstrates metrics collection and calibration analysis

set -euo pipefail

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

echo -e "${BLUE}=== Cleave Metrics Analysis ===${NC}\n"

WORKSPACE=".cleave"

if [ ! -d "$WORKSPACE" ]; then
    echo -e "${YELLOW}Warning: No workspace found at $WORKSPACE${NC}"
    echo "Metrics require completed cleave runs"
    exit 0
fi

echo -e "${GREEN}Step 1: View workspace metrics${NC}"
echo "Shows assessment accuracy for this cleave run"
echo ""

cleave metrics --workspace "$WORKSPACE"

echo -e "\n${GREEN}Step 2: Pattern accuracy breakdown${NC}"
echo "Which patterns have high/low assessment accuracy?"
echo ""

# Extract pattern accuracy from metrics output
if [ -f "$WORKSPACE/metrics.yaml" ]; then
    echo "Metrics file: $WORKSPACE/metrics.yaml"
    echo ""

    # Show pattern-specific metrics
    grep -A 10 "pattern_accuracy" "$WORKSPACE/metrics.yaml" || echo "No pattern accuracy data yet"
fi

echo -e "\n${GREEN}Step 3: Calibration recommendations${NC}"
echo "Suggested adjustments based on assessment accuracy"
echo ""

# Run metrics with analysis flag (if implemented)
cleave metrics --workspace "$WORKSPACE" --analyze 2>/dev/null || echo "Analysis not yet implemented"

echo -e "\n${GREEN}Step 4: Historical trends${NC}"
echo "Track metrics across multiple cleave runs"
echo ""

# Find all metrics files in project
METRICS_FILES=$(find . -path '*/.cleave/metrics.yaml' -type f)

if [ -n "$METRICS_FILES" ]; then
    echo "Found metrics from previous runs:"
    echo "$METRICS_FILES"
    echo ""

    echo "Aggregate metrics (total assessments):"
    grep -h "total_assessments" $METRICS_FILES | awk '{sum+=$2} END {print "Total:", sum}'

    echo ""
    echo "Average complexity (predicted):"
    grep -h "predicted_complexity" $METRICS_FILES | awk '{sum+=$2; count++} END {print "Average:", sum/count}'
else
    echo "No historical metrics found"
fi

echo -e "\n${GREEN}Step 5: Export metrics for analysis${NC}"
echo "Combine metrics from multiple runs for trend analysis"
echo ""

# Create aggregated metrics report
OUTPUT_FILE="metrics-report.json"
echo "Exporting to $OUTPUT_FILE"

# Collect all metrics (requires implementation)
# cleave metrics --export "$OUTPUT_FILE" --recursive

echo ""
echo -e "${BLUE}=== Metrics Analysis Complete ===${NC}"
echo ""
echo -e "${YELLOW}Calibration Tips:${NC}"
echo "1. Review patterns with accuracy < 0.70"
echo "2. Check if systems_base or modifiers need adjustment"
echo "3. Compare predicted vs actual effort across multiple runs"
echo "4. Track improvement over time as patterns are tuned"
echo ""
echo -e "${YELLOW}Feedback Loop:${NC}"
echo "Record → Capture → Calculate → Recommend → Adjust"
