#!/bin/bash
# ============================================================================
# Script de Desenvolvimento Local - Avanzato
# ============================================================================
# Uso: bash scripts/dev.sh [comando]
#
# Comandos:
#   start       - Inicia servidor de desenvolvimento (padrao)
#   build       - Build de producao
#   build-hom   - Build para homologacao
#   preview     - Preview do build local
#   deploy-hom  - Deploy para homologacao
#   deploy-prod - Deploy para producao
#   clean       - Limpa dist/ e node_modules/.cache
#   help        - Mostra esta ajuda
#
# EXEMPLOS:
#   bash scripts/dev.sh start
#   bash scripts/dev.sh build-hom
#   bash scripts/dev.sh deploy-hom
# ============================================================================

set -e

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

# Diretorios
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DIST_DIR="${PROJECT_DIR}/dist"

# Comando
CMD="${1:-start}"

# Banner
show_banner() {
    echo ""
    echo -e "${CYAN}==========================================${NC}"
    echo -e "${CYAN}  Avanzato - Ambiente de Desenvolvimento${NC}"
    echo -e "${CYAN}==========================================${NC}"
    echo ""
}

# Post-build: gerar paginas estaticas para rotas
run_post_build() {
    local dist_dir="${1:-dist}"
    echo -e "${BLUE}[Post-Build]${NC} Gerando paginas estaticas para rotas..."
    bash "${SCRIPT_DIR}/build-static-routes.sh" "$dist_dir"
}

# Verificar dependencias
check_deps() {
    if ! command -v node &> /dev/null; then
        echo -e "${RED}Erro: Node.js nao encontrado!${NC}"
        echo "Instale: https://nodejs.org/ (versao 20+)"
        exit 1
    fi
    if [ ! -d "${PROJECT_DIR}/node_modules" ]; then
        echo -e "${YELLOW}node_modules nao encontrado. Instalando...${NC}"
        cd "$PROJECT_DIR" && npm install
    fi
}

# Start - Desenvolvimento local
cmd_start() {
    show_banner
    check_deps
    echo -e "${GREEN}Iniciando servidor de desenvolvimento...${NC}"
    echo -e "Acesse: ${CYAN}http://localhost:5173${NC}"
    echo ""
    echo -e "${YELLOW}Ambiente: DESENVOLVIMENTO LOCAL${NC}"
    echo -e "- Mautic: ${YELLOW}modo simulacao${NC}"
    echo -e "- Google Ads: ${YELLOW}desativado${NC}"
    echo -e "- Facebook Pixel: ${YELLOW}desativado${NC}"
    echo ""
    cd "$PROJECT_DIR" && npm run dev
}

# Build - Producao
cmd_build() {
    show_banner
    check_deps
    echo -e "${BLUE}[1/2]${NC} Build de PRODUCAO..."
    cd "$PROJECT_DIR"
    npm run build
    echo ""
    echo -e "${BLUE}[2/2]${NC} Configurando robots.txt para producao..."
    cp "${PROJECT_DIR}/public/robots-producao.txt" "${DIST_DIR}/robots.txt"
    echo -e "${GREEN}OK${NC} - Build de producao pronto em dist/"
    
    # Gerar paginas estaticas para rotas
    run_post_build "$DIST_DIR"
    
    echo ""
    echo -e "Para preview: ${CYAN}bash scripts/dev.sh preview${NC}"
}

# Build - Homologacao
cmd_build_hom() {
    show_banner
    check_deps
    echo -e "${YELLOW}[1/2]${NC} Build para HOMOLOGACAO..."
    cd "$PROJECT_DIR"
    npm run build
    echo ""
    echo -e "${YELLOW}[2/2]${NC} Configurando anti-indexacao..."
    # robots.txt ja esta com noindex por padrao
    echo -e "${GREEN}OK${NC} - Build de homologacao pronto em dist/"
    
    # Gerar paginas estaticas para rotas
    run_post_build "$DIST_DIR"
    
    echo ""
    echo -e "Para deploy: ${CYAN}bash scripts/dev.sh deploy-hom${NC}"
}

# Preview do build
cmd_preview() {
    if [ ! -d "$DIST_DIR" ]; then
        echo -e "${RED}Erro: Pasta dist/ nao encontrada!${NC}"
        echo "Execute primeiro: bash scripts/dev.sh build"
        exit 1
    fi
    show_banner
    echo -e "${GREEN}Iniciando preview do build...${NC}"
    echo -e "Acesse: ${CYAN}http://localhost:4173${NC}"
    echo ""
    cd "$PROJECT_DIR" && npm run preview
}

# Deploy Homologacao
cmd_deploy_hom() {
    show_banner
    echo -e "${YELLOW}Deploy para HOMOLOGACAO${NC}"
    echo ""

    # Verificar se dist existe
    if [ ! -d "$DIST_DIR" ]; then
        echo -e "${RED}Erro: dist/ nao encontrado!${NC}"
        echo "Execute: bash scripts/dev.sh build-hom"
        exit 1
    fi

    # Verificar configuracao SSH
    if [ -z "${SSH_HOM_HOST}" ]; then
        echo -e "${YELLOW}Configure as variaveis de ambiente:${NC}"
        echo ""
        echo "  export SSH_HOM_HOST=IP_DO_SERVIDOR_HOM"
        echo "  export SSH_HOM_USER=usuario"
        echo "  export SSH_HOM_PATH=/var/www/avanzato-hom"
        echo ""
        echo "Ou edite o arquivo: ${PROJECT_DIR}/scripts/.env.local"
        echo ""

        # Tentar carregar .env.local
        if [ -f "${PROJECT_DIR}/scripts/.env.local" ]; then
            echo -e "${BLUE}Carregando scripts/.env.local...${NC}"
            source "${PROJECT_DIR}/scripts/.env.local"
        fi

        if [ -z "${SSH_HOM_HOST}" ]; then
            echo -e "${RED}Configuracao nao encontrada. Abortando.${NC}"
            exit 1
        fi
    fi

    echo -e "${BLUE}[1/3]${NC} Verificando conexao..."
    if ! ssh -o ConnectTimeout=10 "${SSH_HOM_USER}@${SSH_HOM_HOST}" "echo 'OK'" 2>/dev/null; then
        echo -e "${RED}Erro: Nao foi possivel conectar ao servidor.${NC}"
        echo "Verifique SSH: ssh-copy-id -i ~/.ssh/id_ed25519.pub ${SSH_HOM_USER}@${SSH_HOM_HOST}"
        exit 1
    fi
    echo -e "${GREEN}OK${NC}"

    echo -e "${BLUE}[2/3]${NC} Enviando arquivos..."
    rsync -avz --delete \
        --exclude='backups' \
        "$DIST_DIR/" \
        "${SSH_HOM_USER}@${SSH_HOM_HOST}:${SSH_HOM_PATH}/"
    echo -e "${GREEN}OK${NC}"

    echo -e "${BLUE}[3/3]${NC} Finalizando..."
    ssh "${SSH_HOM_USER}@${SSH_HOM_HOST}" "sudo systemctl reload nginx 2>/dev/null || true"

    echo ""
    echo -e "${GREEN}Deploy para HOMOLOGACAO concluido!${NC}"
    echo -e "Acesse: ${CYAN}https://homologacao.avanzato.com.br${NC}"
    echo ""
}

# Deploy Producao
cmd_deploy_prod() {
    show_banner
    echo -e "${RED} Deploy para PRODUCAO${NC}"
    echo ""

    # Verificar se dist existe
    if [ ! -d "$DIST_DIR" ]; then
        echo -e "${RED}Erro: dist/ nao encontrado!${NC}"
        echo "Execute: bash scripts/dev.sh build"
        exit 1
    fi

    # Verificar configuracao SSH
    if [ -z "${SSH_PROD_HOST}" ]; then
        echo -e "${YELLOW}Configure as variaveis de ambiente:${NC}"
        echo ""
        echo "  export SSH_PROD_HOST=IP_DO_SERVIDOR_PROD"
        echo "  export SSH_PROD_USER=usuario"
        echo "  export SSH_PROD_PATH=/var/www/avanzato"
        echo ""

        # Tentar carregar .env.local
        if [ -f "${PROJECT_DIR}/scripts/.env.local" ]; then
            echo -e "${BLUE}Carregando scripts/.env.local...${NC}"
            source "${PROJECT_DIR}/scripts/.env.local"
        fi

        if [ -z "${SSH_PROD_HOST}" ]; then
            echo -e "${RED}Configuracao nao encontrada. Abortando.${NC}"
            exit 1
        fi
    fi

    echo -e "${RED} ============================================${NC}"
    echo -e "${RED}  ATENCAO: Deploy para PRODUCAO${NC}"
    echo -e "${RED} ============================================${NC}"
    echo ""
    read -p "Tem certeza que deseja deploy para PRODUCAO? (digite 'sim' para confirmar): " confirm
    if [ "$confirm" != "sim" ]; then
        echo -e "${YELLOW}Deploy cancelado.${NC}"
        exit 0
    fi

    echo -e "${BLUE}[1/4]${NC} Verificando conexao..."
    if ! ssh -o ConnectTimeout=10 "${SSH_PROD_USER}@${SSH_PROD_HOST}" "echo 'OK'" 2>/dev/null; then
        echo -e "${RED}Erro: Nao foi possivel conectar ao servidor.${NC}"
        exit 1
    fi
    echo -e "${GREEN}OK${NC}"

    echo -e "${BLUE}[2/4]${NC} Criando backup..."
    ssh "${SSH_PROD_USER}@${SSH_PROD_HOST}" "
        if [ -d '${SSH_PROD_PATH}' ]; then
            mkdir -p '${SSH_PROD_PATH}/backups'
            cp -r '${SSH_PROD_PATH}' '${SSH_PROD_PATH}/backups/backup-$(date +%Y%m%d-%H%M%S)' 2>/dev/null || true
        fi
    " 2>/dev/null || echo -e "${YELLOW}Backup ignorado.${NC}"

    echo -e "${BLUE}[3/4]${NC} Enviando arquivos..."
    rsync -avz --delete \
        --exclude='backups' \
        "$DIST_DIR/" \
        "${SSH_PROD_USER}@${SSH_PROD_HOST}:${SSH_PROD_PATH}/"
    echo -e "${GREEN}OK${NC}"

    echo -e "${BLUE}[4/4]${NC} Finalizando..."
    ssh "${SSH_PROD_USER}@${SSH_PROD_HOST}" "sudo systemctl reload nginx 2>/dev/null || true"

    echo ""
    echo -e "${GREEN}Deploy para PRODUCAO concluido!${NC}"
    echo -e "Acesse: ${CYAN}https://avanzato.com.br${NC}"
    echo ""
}

# Clean
cmd_clean() {
    show_banner
    echo -e "${YELLOW}Limpando caches...${NC}"
    rm -rf "${DIST_DIR}"
    rm -rf "${PROJECT_DIR}/node_modules/.cache"
    rm -rf "${PROJECT_DIR}/node_modules/.vite"
    echo -e "${GREEN}OK${NC} - Caches limpos"
}

# Help
cmd_help() {
    echo ""
    echo -e "${CYAN}Avanzato - Script de Desenvolvimento${NC}"
    echo ""
    echo -e "Uso: ${YELLOW}bash scripts/dev.sh [comando]${NC}"
    echo ""
    echo -e "${GREEN}Comandos disponiveis:${NC}"
    echo ""
    echo "  ${YELLOW}start${NC}       Inicia servidor dev (http://localhost:5173)"
    echo "  ${YELLOW}build${NC}       Build de producao"
    echo "  ${YELLOW}build-hom${NC}   Build para homologacao"
    echo "  ${YELLOW}preview${NC}     Preview do build local (http://localhost:4173)"
    echo "  ${YELLOW}deploy-hom${NC}  Deploy para servidor de homologacao"
    echo "  ${YELLOW}deploy-prod${NC} Deploy para servidor de producao"
    echo "  ${YELLOW}clean${NC}       Limpa dist/ e caches"
    echo "  ${YELLOW}help${NC}        Mostra esta ajuda"
    echo ""
    echo -e "${GREEN}Fluxo de trabalho:${NC}"
    echo ""
    echo "  1. Desenvolva:  bash scripts/dev.sh start"
    echo "  2. Build hom:   bash scripts/dev.sh build-hom"
    echo "  3. Deploy hom:  bash scripts/dev.sh deploy-hom"
    echo "  4. Aprove..."
    echo "  5. Build prod:  bash scripts/dev.sh build"
    echo "  6. Deploy prod: bash scripts/dev.sh deploy-prod"
    echo ""
}

# Dispatcher
case "$CMD" in
    start|dev)
        cmd_start
        ;;
    build)
        cmd_build
        ;;
    build-hom|build-homolog|build-staging)
        cmd_build_hom
        ;;
    preview)
        cmd_preview
        ;;
    deploy-hom|deploy-homolog|deploy-staging)
        cmd_deploy_hom
        ;;
    deploy-prod|deploy-production)
        cmd_deploy_prod
        ;;
    clean)
        cmd_clean
        ;;
    help|--help|-h)
        cmd_help
        ;;
    *)
        echo -e "${RED}Comando desconhecido: ${CMD}${NC}"
        cmd_help
        exit 1
        ;;
esac
