#!/bin/bash
# =============================================================================
# SCRIPT: validate-capved-gate.sh
# PROPOSITO: Verificar que una tarea ha completado todas las fases CAPVED
# SISTEMA: SIMCO + CAPVED
# VERSION: 1.0.0
# =============================================================================

set -e

WORKSPACE_ROOT="${HOME}/workspace"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

PROJECT="${1:-}"
TASK_ID="${2:-}"

echo "=============================================="
echo "  VALIDACION GATE CAPVED"
echo "=============================================="
echo ""

if [ -z "$PROJECT" ] || [ -z "$TASK_ID" ]; then
    echo "Uso: $0 <proyecto> <task_id>"
    echo "Ejemplo: $0 gamilit HU-001"
    exit 1
fi

PROJECT_PATH="${WORKSPACE_ROOT}/projects/${PROJECT}"
ORCH_PATH="${PROJECT_PATH}/orchestration"

if [ ! -d "$PROJECT_PATH" ]; then
    echo -e "${RED}ERROR: Proyecto no existe: $PROJECT${NC}"
    exit 1
fi

PASSED=0
FAILED=0

echo "Proyecto: $PROJECT"
echo "Tarea: $TASK_ID"
echo ""

# -----------------------------------------------------------------------------
# Fase C - CONTEXTO
# -----------------------------------------------------------------------------
echo -e "${BLUE}=== FASE C: CONTEXTO ===${NC}"

check_contexto() {
    # Verificar que CONTEXTO-PROYECTO.md existe
    if [ -f "${ORCH_PATH}/00-guidelines/CONTEXTO-PROYECTO.md" ]; then
        echo -e "${GREEN}[OK]${NC} CONTEXTO-PROYECTO.md existe"
        ((PASSED++))
    else
        echo -e "${RED}[FAIL]${NC} CONTEXTO-PROYECTO.md no existe"
        ((FAILED++))
    fi

    # Verificar HERENCIA-SIMCO.md
    if [ -f "${ORCH_PATH}/00-guidelines/HERENCIA-SIMCO.md" ]; then
        echo -e "${GREEN}[OK]${NC} HERENCIA-SIMCO.md existe"
        ((PASSED++))
    else
        echo -e "${RED}[FAIL]${NC} HERENCIA-SIMCO.md no existe"
        ((FAILED++))
    fi
}

check_contexto

# -----------------------------------------------------------------------------
# Fase A - ANALISIS
# -----------------------------------------------------------------------------
echo ""
echo -e "${BLUE}=== FASE A: ANALISIS ===${NC}"

check_analisis() {
    # Verificar si existe archivo de analisis para la tarea
    local analisis_file="${ORCH_PATH}/01-analisis/${TASK_ID}-analisis.md"
    local analisis_impacto="${ORCH_PATH}/01-analisis/${TASK_ID}-impacto.md"

    if [ -f "$analisis_file" ] || [ -f "$analisis_impacto" ]; then
        echo -e "${GREEN}[OK]${NC} Analisis documentado"
        ((PASSED++))
    else
        echo -e "${YELLOW}[WARN]${NC} No se encontro archivo de analisis especifico"
        echo "       Buscar en: ${ORCH_PATH}/01-analisis/"
    fi

    # Verificar que inventarios fueron consultados
    if [ -f "${ORCH_PATH}/inventarios/MASTER_INVENTORY.yml" ]; then
        echo -e "${GREEN}[OK]${NC} MASTER_INVENTORY disponible para consulta"
        ((PASSED++))
    else
        echo -e "${RED}[FAIL]${NC} MASTER_INVENTORY.yml no existe"
        ((FAILED++))
    fi
}

check_analisis

# -----------------------------------------------------------------------------
# Fase P - PLANEACION
# -----------------------------------------------------------------------------
echo ""
echo -e "${BLUE}=== FASE P: PLANEACION ===${NC}"

check_planeacion() {
    # Verificar si existe plan para la tarea
    local plan_file="${ORCH_PATH}/02-planeacion/${TASK_ID}-plan.md"

    if [ -f "$plan_file" ]; then
        echo -e "${GREEN}[OK]${NC} Plan documentado: $plan_file"
        ((PASSED++))
    else
        echo -e "${YELLOW}[WARN]${NC} No se encontro archivo de plan especifico"
        echo "       Buscar en: ${ORCH_PATH}/02-planeacion/"
    fi
}

check_planeacion

# -----------------------------------------------------------------------------
# Fase V - VALIDACION
# -----------------------------------------------------------------------------
echo ""
echo -e "${BLUE}=== FASE V: VALIDACION ===${NC}"

check_validacion() {
    # Verificar si existe validacion para la tarea
    local val_file="${ORCH_PATH}/05-validaciones/${TASK_ID}-validacion.md"

    if [ -f "$val_file" ]; then
        echo -e "${GREEN}[OK]${NC} Validacion documentada"
        ((PASSED++))
    else
        echo -e "${YELLOW}[WARN]${NC} No se encontro archivo de validacion especifico"
    fi

    # Verificar que documentos de impacto existen en core
    if [ -f "${WORKSPACE_ROOT}/core/orchestration/impactos/MATRIZ-DEPENDENCIAS.md" ]; then
        echo -e "${GREEN}[OK]${NC} MATRIZ-DEPENDENCIAS.md disponible"
        ((PASSED++))
    else
        echo -e "${RED}[FAIL]${NC} MATRIZ-DEPENDENCIAS.md no existe en core"
        ((FAILED++))
    fi
}

check_validacion

# -----------------------------------------------------------------------------
# Fase E - EJECUCION
# -----------------------------------------------------------------------------
echo ""
echo -e "${BLUE}=== FASE E: EJECUCION ===${NC}"

check_ejecucion() {
    # Verificar logs de ejecucion
    local log_file="${ORCH_PATH}/04-ejecucion-logs/${TASK_ID}-log.md"

    if [ -f "$log_file" ]; then
        echo -e "${GREEN}[OK]${NC} Log de ejecucion documentado"
        ((PASSED++))
    else
        echo -e "${YELLOW}[WARN]${NC} No se encontro log de ejecucion especifico"
    fi

    # Verificar builds
    echo -e "${YELLOW}[INFO]${NC} Verificar manualmente: npm run build && npm run lint"
}

check_ejecucion

# -----------------------------------------------------------------------------
# Fase D - DOCUMENTACION
# -----------------------------------------------------------------------------
echo ""
echo -e "${BLUE}=== FASE D: DOCUMENTACION ===${NC}"

check_documentacion() {
    # Verificar que trazas estan actualizadas
    local has_traza=false

    for traza in "${ORCH_PATH}/trazas/"TRAZA-*.md; do
        if [ -f "$traza" ]; then
            # Buscar mencion de la tarea en trazas
            if grep -q "$TASK_ID" "$traza" 2>/dev/null; then
                echo -e "${GREEN}[OK]${NC} Tarea registrada en: $(basename $traza)"
                has_traza=true
                ((PASSED++))
                break
            fi
        fi
    done

    if [ "$has_traza" = false ]; then
        echo -e "${RED}[FAIL]${NC} Tarea no encontrada en ninguna traza"
        ((FAILED++))
    fi

    # Verificar PROXIMA-ACCION actualizado
    if [ -f "${ORCH_PATH}/PROXIMA-ACCION.md" ]; then
        local last_modified=$(stat -c %Y "${ORCH_PATH}/PROXIMA-ACCION.md" 2>/dev/null || stat -f %m "${ORCH_PATH}/PROXIMA-ACCION.md" 2>/dev/null)
        local now=$(date +%s)
        local diff=$((now - last_modified))
        local hours=$((diff / 3600))

        if [ $hours -lt 24 ]; then
            echo -e "${GREEN}[OK]${NC} PROXIMA-ACCION.md actualizado recientemente"
            ((PASSED++))
        else
            echo -e "${YELLOW}[WARN]${NC} PROXIMA-ACCION.md no actualizado en $hours horas"
        fi
    else
        echo -e "${RED}[FAIL]${NC} PROXIMA-ACCION.md no existe"
        ((FAILED++))
    fi

    # Verificar inventarios actualizados
    echo -e "${YELLOW}[INFO]${NC} Verificar manualmente: Inventarios actualizados con cambios"
}

check_documentacion

# -----------------------------------------------------------------------------
# RESUMEN
# -----------------------------------------------------------------------------
echo ""
echo "=============================================="
echo "  RESUMEN GATE CAPVED"
echo "=============================================="
echo ""

TOTAL=$((PASSED + FAILED))

echo "Checks pasados: $PASSED / $TOTAL"
echo "Checks fallidos: $FAILED"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}=============================================="
    echo "  GATE CAPVED: APROBADO"
    echo "==============================================${NC}"
    echo ""
    echo "La tarea $TASK_ID puede considerarse COMPLETADA."
    exit 0
else
    echo -e "${RED}=============================================="
    echo "  GATE CAPVED: NO APROBADO"
    echo "==============================================${NC}"
    echo ""
    echo "Corrige los items fallidos antes de cerrar la tarea."
    exit 1
fi
