"""
@RAG_CONTEXT
{
  "archivo": "src/rag_indexer/hook_manager.py",
  "lineas": 41,
  "tokens_estimados": 330,
  "hash_contenido": "ebe4bb0b74f0945af839dc5f1021c572e334ccdcf3f82789b21417e24e126d91",
  "creacion": "2026-03-04",
  "modificacion": "2026-03-04",
  "tags": [
    "stat",
    "os"
  ],
  "descripcion_corta": "",
  "descripcion_larga": ""
}
"""
import os
import stat

HOOK_CONTENT = """#!/bin/bash
# Autogenerated by rag-indexer
echo "========================================================"
echo "🤖 Ejecutando RAG Indexer (Generación de Contexto LLM)..."
echo "========================================================"
if [ -f .env ]; then export $(grep -v '^#' .env | xargs); fi
rag-indexer run
if [ $? -ne 0 ]; then
  echo "❌ Error: RAG Indexer falló. Commit abortado."
  exit 1
fi
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)
if [ -z "$STAGED_FILES" ]; then exit 0; fi
for FILE in $STAGED_FILES; do
  if [ -f "$FILE" ]; then git add "$FILE"; fi
done
git add rag-indexer.json
echo "✅ Contexto RAG indexado y archivos listos."
exit 0
"""


def install_git_hook():
    git_dir = os.path.join(os.getcwd(), '.git')
    if not os.path.exists(git_dir):
        print("❌ Error: No se encontró directorio .git. Ejecuta en la raíz de tu proyecto.")
        return

    hooks_dir = os.path.join(git_dir, 'hooks')
    os.makedirs(hooks_dir, exist_ok=True)

    hook_path = os.path.join(hooks_dir, 'pre-commit')
    with open(hook_path, 'w', encoding='utf-8') as f:
        f.write(HOOK_CONTENT)

    st = os.stat(hook_path)
    os.chmod(hook_path, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
    print(f"✅ Git Hook instalado en {hook_path}")
