#!/bin/bash

# ---
# Gemini Audit Script - v0.1 (Generic)
# ---

# 1. Configuration
REPORT_DIR="../../reports" # Go up two levels from .gemini/commands to the project root
TIMESTAMP=$(date +"%Y%m%d%H%M%S")
REPORT_FILE="$REPORT_DIR/gemini-audit-$TIMESTAMP.md"
PROJECT_NAME=$(basename "$(dirname "$(dirname "$PWD")")") # Get project name from path

# Directories to ignore in searches
# We are running from .gemini/commands, so we need to adjust paths
# We will search in ../../ which is the project root
SEARCH_PATH="../../"
EXCLUDE_DIRS=("--exclude-dir=node_modules" "--exclude-dir=vendor" "--exclude-dir=.git" "--exclude-dir=dist" "--exclude-dir=build" "--exclude-dir=.gemini")

# 2. Setup
mkdir -p "$REPORT_DIR"
echo "Creating report at $REPORT_FILE"

# 3. Report Header
echo "# 🛡️ Relatório de Auditoria - $PROJECT_NAME" > "$REPORT_FILE"
echo "**Data**: $(date +"%Y-%m-%d %H:%M:%S")" >> "$REPORT_FILE"
echo "**Versão**: (a ser preenchido)" >> "$REPORT_FILE"
echo "**Score**: (a ser calculado)" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
echo "## 📊 Resumo Executivo" >> "$REPORT_FILE"
echo "- Vulnerabilidades críticas: (a calcular)" >> "$REPORT_FILE"
echo "- Vulnerabilidades médias: (a calcular)" >> "$REPORT_FILE"
echo "- Vulnerabilidades baixas: (a calcular)" >> "$REPORT_FILE"
echo "- Problemas de qualidade: (a calcular)" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# 4. Analysis
echo "## 🚨 Vulnerabilidades Críticas" >> "$REPORT_FILE"
echo "### Detecção de Segredos Hardcoded" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Using grep to find potential secrets. This is a basic check.
# We search for common keywords and patterns.
grep -rniE "(api_key|secret_key|password|token|credentials|auth_token|access_key)" "${EXCLUDE_DIRS[@]}" "$SEARCH_PATH" >> "$REPORT_FILE" || echo "Nenhum segredo hardcoded encontrado com o padrão básico." >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"


echo "## 📦 Dependências" >> "$REPORT_FILE"
echo "### Ficheiros de Dependências Encontrados" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

if [ -f "$SEARCH_PATH/package.json" ]; then
    echo "- Encontrado: package.json (Projeto Node.js/JavaScript)" >> "$REPORT_FILE"
fi
if [ -f "$SEARCH_PATH/composer.json" ]; then
    echo "- Encontrado: composer.json (Projeto PHP/Composer)" >> "$REPORT_FILE"
fi
if [ -f "$SEARCH_PATH/requirements.txt" ]; then
    echo "- Encontrado: requirements.txt (Projeto Python/pip)" >> "$REPORT_FILE"
fi
if [ -f "$SEARCH_PATH/pom.xml" ]; then
    echo "- Encontrado: pom.xml (Projeto Java/Maven)" >> "$REPORT_FILE"
fi
if [ -f "$SEARCH_PATH/build.gradle" ]; then
    echo "- Encontrado: build.gradle (Projeto Java/Gradle)" >> "$REPORT_FILE"
fi

echo "" >> "$REPORT_FILE"
echo "Auditoria inicial concluída. O relatório foi gerado em $REPORT_FILE"
