#!/bin/bash

# MORPH-SPEC Pre-commit Hook: Cost Validation
#
# Valida custos de arquivos Bicep antes de permitir commit.
# Bloqueia commits que excedem o limite configurado sem ADR.
#
# Instalação:
#   cp .morph/hooks/pre-commit-costs.sh .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#
# Ou use symlink:
#   ln -s ../../.morph/hooks/pre-commit-costs.sh .git/hooks/pre-commit

set -e

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

echo -e "${GREEN}🔍 MORPH-SPEC: Validating infrastructure costs...${NC}"

# Encontrar arquivos Bicep modificados no staged area
BICEP_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.bicep$' || true)

if [ -z "$BICEP_FILES" ]; then
  echo -e "${GREEN}✓ No Bicep files changed, skipping cost validation.${NC}"
  exit 0
fi

echo "Found Bicep files:"
echo "$BICEP_FILES" | sed 's/^/  - /'

# Rodar cost calculator
RESULT=$(node bin/calculate-costs.js $BICEP_FILES --json 2>&1)
EXIT_CODE=$?

# Parse result JSON
MONTHLY_COST=$(echo "$RESULT" | grep -o '"monthly":[^,]*' | cut -d':' -f2 | tr -d ' ')
REQUIRES_ADR=$(echo "$RESULT" | grep -o '"requiresADR":[^,]*' | cut -d':' -f2 | tr -d ' ')

echo -e "\n${YELLOW}Estimated Monthly Cost: \$${MONTHLY_COST}${NC}"

# Se não requer ADR, aprovar
if [ "$REQUIRES_ADR" != "true" ]; then
  echo -e "${GREEN}✓ Cost is within limits. Proceeding with commit.${NC}"
  exit 0
fi

# Se requer ADR, verificar se existe decisions.md com ADR de custo
echo -e "\n${YELLOW}⚠️  Cost exceeds ADR threshold!${NC}"
echo "Checking for cost ADR in decisions.md..."

# Procurar decisions.md em outputs de features
DECISIONS_FILES=$(find .morph/project/outputs -name "decisions.md" 2>/dev/null || true)

ADR_FOUND=false

for file in $DECISIONS_FILES; do
  # Procurar por ADR que menciona "cost" ou "Infrastructure Costs"
  if grep -qi "ADR.*cost\|Infrastructure Costs" "$file"; then
    echo -e "${GREEN}✓ Found cost ADR in: $file${NC}"
    ADR_FOUND=true
    break
  fi
done

if [ "$ADR_FOUND" = true ]; then
  echo -e "${GREEN}✓ Cost ADR documented. Proceeding with commit.${NC}"
  exit 0
else
  echo -e "${RED}❌ COMMIT BLOCKED!${NC}"
  echo ""
  echo "Monthly cost (\$$MONTHLY_COST) exceeds the configured ADR threshold."
  echo ""
  echo "To proceed, you must:"
  echo "  1. Document a cost ADR in .morph/project/outputs/{feature}/decisions.md"
  echo "  2. Include justification for infrastructure costs"
  echo ""
  echo "Example ADR:"
  echo "  ## ADR-XXX: Infrastructure Costs"
  echo "  "
  echo "  **Estimated Monthly Cost:** \$$MONTHLY_COST"
  echo "  "
  echo "  **Justification:**"
  echo "  {Why these resources are necessary and cost-effective}"
  echo ""
  exit 1
fi
