#!/bin/bash
# ============================================================================
# Script de Deploy Manual - Avanzato
# ============================================================================
# Uso: bash deploy-manual.sh [caminho-do-build.zip]
#
# Exemplo:
#   bash deploy-manual.sh /caminho/avanzato-site-build.zip
#
# Se nao passar argumento, procura avanzato-site-build.zip no diretorio atual
# ============================================================================

set -e

# =============================================================================
# CONFIGURACOES - AJUSTE SE NECESSARIO
# =============================================================================

# Caminho do site no servidor
SITE_PATH="/opt/avanzato/site/app"

# Container Docker
CONTAINER_NAME="avanzato-site"

# Porta do site
SITE_PORT="8080"

# Dominio
DOMAIN="avanzato.com.br"

# Mautic URL (para validacao)
MAUTIC_URL="mkt.avanzato.com.br"

# =============================================================================
# CORES
# =============================================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'
BOLD='\033[1m'

# =============================================================================
# FUNCOES DE UTILIDADE
# =============================================================================

print_header() {
    echo ""
    echo -e "${CYAN}============================================================${NC}"
    echo -e "${CYAN}  $1${NC}"
    echo -e "${CYAN}============================================================${NC}"
    echo ""
}

print_step() {
    echo -e "${BLUE}[PASSO $1]${NC} $2"
}

print_ok() {
    echo -e "${GREEN}  ✓${NC} $1"
}

print_error() {
    echo -e "${RED}  ✗ ERRO:${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}  ⚠ AVISO:${NC} $1"
}

print_info() {
    echo -e "${CYAN}  ℹ${NC} $1"
}

confirm() {
    read -p "$1 (s/N): " response
    case "$response" in
        [sS]) return 0 ;;
        *) return 1 ;;
    esac
}

# =============================================================================
# VALIDACAO INICIAL
# =============================================================================

print_header "DEPLOY MANUAL - AVANZATO"

# Verificar se esta no servidor correto
if [ ! -d "$SITE_PATH" ]; then
    print_error "Diretorio do site nao encontrado: $SITE_PATH"
    print_info "Verifique se esta no servidor correto"
    exit 1
fi

print_ok "Diretorio do site encontrado: $SITE_PATH"

# Verificar se Docker esta rodando
if ! docker ps &>/dev/null; then
    print_error "Docker nao esta acessivel. Verifique permissoes."
    exit 1
fi

print_ok "Docker acessivel"

# Verificar arquivo de build
BUILD_FILE="${1:-avanzato-site-build.zip}"

if [ ! -f "$BUILD_FILE" ]; then
    print_error "Arquivo de build nao encontrado: $BUILD_FILE"
    print_info "Uso: bash deploy-manual.sh /caminho/do/build.zip"
    print_info "Ou coloque avanzato-site-build.zip nesta pasta"
    
    # Listar arquivos zip disponiveis
    zips=$(find . -maxdepth 1 -name "*.zip" -type f 2>/dev/null)
    if [ -n "$zips" ]; then
        echo ""
        print_info "Arquivos zip encontrados:"
        echo "$zips" | while read f; do echo "  - $f ($(du -h "$f" | cut -f1))"; done
    fi
    exit 1
fi

print_ok "Arquivo de build encontrado: $BUILD_FILE ($(du -h "$BUILD_FILE" | cut -f1))"

# =============================================================================
# PASSO 1: BACKUP DO DIST ATUAL
# =============================================================================

print_step "1" "Backup do dist atual"

if [ -d "$SITE_PATH/dist" ]; then
    BACKUP_NAME="dist_bkp_$(date +%Y%m%d_%H%M)"
    cp -r "$SITE_PATH/dist" "$SITE_PATH/$BACKUP_NAME"
    print_ok "Backup criado: $SITE_PATH/$BACKUP_NAME"
else
    print_warning "Dist atual nao encontrado, pulando backup"
fi

# =============================================================================
# PASSO 2: ENVIAR/EXTRAIR NOVO BUILD
# =============================================================================

print_step "2" "Extrair novo build"

# Criar diretorio temporario
TEMP_DIR="/tmp/avanzato-deploy-$(date +%s)"
mkdir -p "$TEMP_DIR"

# Extrair
unzip -q "$BUILD_FILE" -d "$TEMP_DIR"
print_ok "Build extraido para $TEMP_DIR"

# Verificar estrutura
if [ -d "$TEMP_DIR/dist" ]; then
    DIST_SOURCE="$TEMP_DIR/dist"
elif [ -d "$TEMP_DIR/app/dist" ]; then
    DIST_SOURCE="$TEMP_DIR/app/dist"
else
    print_error "Estrutura do zip invalida. Esperado: dist/ ou app/dist/"
    print_info "Conteudo do zip:"
    find "$TEMP_DIR" -maxdepth 2 -type d
    rm -rf "$TEMP_DIR"
    exit 1
fi

print_ok "Dist encontrado em: $DIST_SOURCE"

# =============================================================================
# PASSO 3: VALIDAR NOVO DIST
# =============================================================================

print_step "3" "Validar novo dist"

# Verificar index.html
if [ ! -f "$DIST_SOURCE/index.html" ]; then
    print_error "index.html nao encontrado no novo dist!"
    rm -rf "$TEMP_DIR"
    exit 1
fi
print_ok "index.html existe"

# Verificar assets
if [ ! -d "$DIST_SOURCE/assets" ]; then
    print_error "Pasta assets/ nao encontrada!"
    rm -rf "$TEMP_DIR"
    exit 1
fi
print_ok "assets/ existe ($(ls "$DIST_SOURCE/assets/" | wc -l) arquivos)"

# Verificar favicon
if [ -f "$DIST_SOURCE/favicon.svg" ] || [ -f "$DIST_SOURCE/favicon.ico" ]; then
    print_ok "favicon existe"
else
    print_warning "favicon nao encontrado (opcional)"
fi

# Verificar Mautic no codigo
if grep -q "$MAUTIC_URL" "$DIST_SOURCE/index.html" 2>/dev/null; then
    print_ok "Mautic ($MAUTIC_URL) encontrado no index.html"
else
    print_warning "URL do Mautic nao encontrada no index.html"
fi

# Verificar Facebook Pixel
if grep -q "1223271852059785" "$DIST_SOURCE/index.html" 2>/dev/null; then
    print_ok "Facebook Pixel encontrado no index.html"
else
    print_warning "Facebook Pixel nao encontrado no index.html"
fi

# Verificar Google Ads
if grep -q "AW-16714813566" "$DIST_SOURCE/index.html" 2>/dev/null; then
    print_ok "Google Ads encontrado no index.html"
else
    print_warning "Google Ads nao encontrado no index.html"
fi

# =============================================================================
# PASSO 4: CONFIRMAR DEPLOY
# =============================================================================

echo ""
print_info "Resumo do deploy:"
echo "  Build: $BUILD_FILE"
echo "  Dist origem: $DIST_SOURCE"
echo "  Dist destino: $SITE_PATH/dist"
echo "  Container: $CONTAINER_NAME"
echo ""

if ! confirm "Confirma o deploy?"; then
    print_warning "Deploy cancelado pelo usuario"
    rm -rf "$TEMP_DIR"
    exit 0
fi

# =============================================================================
# PASSO 5: SUBSTITUIR DIST
# =============================================================================

print_step "5" "Substituir dist"

# Remover dist antigo
if [ -d "$SITE_PATH/dist" ]; then
    rm -rf "$SITE_PATH/dist"
    print_ok "Dist antigo removido"
fi

# Copiar novo dist
cp -r "$DIST_SOURCE" "$SITE_PATH/dist"
print_ok "Novo dist copiado para $SITE_PATH/dist"

# Ajustar permissoes
chown -R root:root "$SITE_PATH/dist" 2>/dev/null || true
chmod -R 755 "$SITE_PATH/dist" 2>/dev/null || true

# =============================================================================
# PASSO 6: VALIDAR ARQUIVOS
# =============================================================================

print_step "6" "Validar arquivos do novo dist"

if [ ! -f "$SITE_PATH/dist/index.html" ]; then
    print_error "index.html nao encontrado apos copiar!"
    exit 1
fi
print_ok "index.html presente"

if [ ! -d "$SITE_PATH/dist/assets" ]; then
    print_error "assets/ nao encontrado apos copiar!"
    exit 1
fi
print_ok "assets/ presente ($(ls "$SITE_PATH/dist/assets/" | wc -l) arquivos)"

# Mostrar tamanho
DIST_SIZE=$(du -sh "$SITE_PATH/dist" | cut -f1)
print_info "Tamanho do dist: $DIST_SIZE"

# =============================================================================
# PASSO 7: REINICIAR CONTAINER
# =============================================================================

print_step "7" "Reiniciar container Docker"

cd "$SITE_PATH"

docker compose down
print_ok "Container parado"

docker compose up -d
print_ok "Container iniciado"

# Aguardar container subir
print_info "Aguardando container iniciar..."
sleep 5

# =============================================================================
# PASSO 8: VALIDAR CONTAINER
# =============================================================================

print_step "8" "Validar container"

if docker ps --format "{{.Names}}" | grep -q "$CONTAINER_NAME"; then
    print_ok "Container '$CONTAINER_NAME' esta rodando"
else
    print_error "Container '$CONTAINER_NAME' NAO encontrado!"
    docker ps
    exit 1
fi

# =============================================================================
# PASSO 9: TESTAR LOCALMENTE
# =============================================================================

print_step "9" "Testar localmente"

# Testar HTTP
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$SITE_PORT 2>/dev/null || echo "000")

if [ "$HTTP_STATUS" = "200" ]; then
    print_ok "HTTP 200 OK - Site responde na porta $SITE_PORT"
else
    print_error "HTTP $HTTP_STATUS - Site nao responde corretamente"
    print_info "Aguardando mais 5 segundos..."
    sleep 5
    HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$SITE_PORT 2>/dev/null || echo "000")
    if [ "$HTTP_STATUS" = "200" ]; then
        print_ok "HTTP 200 OK - Site responde agora"
    else
        print_error "HTTP $HTTP_STATUS - Problema persistente"
    fi
fi

# Validar Mautic no HTML
if curl -s http://127.0.0.1:$SITE_PORT | grep -q "$MAUTIC_URL"; then
    print_ok "Mautic ($MAUTIC_URL) encontrado no HTML"
else
    print_warning "Mautic nao encontrado no HTML"
fi

# =============================================================================
# PASSO 10: LIMPAR CACHE CLOUDFLARE
# =============================================================================

print_step "10" "Limpar cache Cloudflare"

print_info "Execute manualmente no painel Cloudflare:"
echo ""
echo -e "  ${CYAN}1.${NC} Acesse: https://dash.cloudflare.com"
echo -e "  ${CYAN}2.${NC} Selecione o dominio: $DOMAIN"
echo -e "  ${CYAN}3.${NC} Va em: Caching → Configuration"
echo -e "  ${CYAN}4.${NC} Clique: ${BOLD}Purge Everything${NC}"
echo -e "  ${CYAN}5.${NC} Ative: ${BOLD}Development Mode → ON${NC}"
echo ""

if confirm "Ja limpou o cache do Cloudflare"; then
    print_ok "Cache limpo"
else
    print_warning "Lembre-se de limpar o cache manualmente!"
fi

# =============================================================================
# PASSO 11: TESTAR NO NAVEGADOR
# =============================================================================

print_step "11" "Testar no navegador"

echo ""
print_info "URLs para testar:"
echo -e "  ${CYAN}1.${NC} https://$DOMAIN/?v=$(date +%Y%m%d)"
echo -e "  ${CYAN}2.${NC} https://$DOMAIN/contato"
echo -e "  ${CYAN}3.${NC} https://$DOMAIN/avaliacao"
echo -e "  ${CYAN}4.${NC} https://$DOMAIN/tecnologia-para-condominios"
echo ""

if confirm "Deseja abrir o site no navegador agora (via curl)"; then
    echo ""
    print_info "Testando pagina principal..."
    curl -I "https://$DOMAIN/?v=$(date +%Y%m%d)" 2>/dev/null | head -5 || \
        print_warning "Nao foi possivel testar via HTTPS (pode ser normal)"
fi

# =============================================================================
# PASSO 12: LIMPAR TEMP
# =============================================================================

print_step "12" "Limpar arquivos temporarios"

rm -rf "$TEMP_DIR"
print_ok "Arquivos temporarios removidos"

# =============================================================================
# RESUMO FINAL
# =============================================================================

echo ""
print_header "DEPLOY CONCLUIDO!"

echo -e "${GREEN}Site atualizado com sucesso!${NC}"
echo ""
echo -e "  Build: ${CYAN}$BUILD_FILE${NC}"
echo -e "  Dist: ${CYAN}$SITE_PATH/dist${NC}"
echo -e "  Container: ${CYAN}$CONTAINER_NAME${NC}"
echo -e "  Porta: ${CYAN}$SITE_PORT${NC}"
echo ""

echo -e "${YELLOW}Proximos passos:${NC}"
echo -e "  1. Limpar cache Cloudflare (se ainda nao fez)"
echo -e "  2. Testar no navegador: https://$DOMAIN"
echo -e "  3. Testar formularios"
echo -e "  4. Verificar leads no Mautic"
echo ""

echo -e "${YELLOW}Em caso de problema:${NC}"
echo -e "  1. Restaurar backup: ${CYAN}cp -r $SITE_PATH/dist_bkp_* $SITE_PATH/dist${NC}"
echo -e "  2. Reiniciar: ${CYAN}cd $SITE_PATH && docker compose down && docker compose up -d${NC}"
echo -e "  3. Limpar cache Safari: ${CYAN}CMD + OPTION + E${NC}"
echo ""
