import os
import sys

def update_api_key(api_key):
    """
    Actualiza la API key de OpenAI en views.py
    """
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ai_agent', 'views.py')
    
    try:
        # Leemos el contenido actual del archivo
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        
        # Reemplazamos la API key
        if 'os.environ["OPENAI_API_KEY"] = "tu-api-key-aquí"' in content:
            updated_content = content.replace(
                'os.environ["OPENAI_API_KEY"] = "tu-api-key-aquí"',
                f'os.environ["OPENAI_API_KEY"] = "{api_key}"'
            )
        elif 'os.environ["OPENAI_API_KEY"] = "tu-api-key"' in content:
            updated_content = content.replace(
                'os.environ["OPENAI_API_KEY"] = "tu-api-key"',
                f'os.environ["OPENAI_API_KEY"] = "{api_key}"'
            )
        else:
            print("No se pudo encontrar la línea para actualizar la API key.")
            return False
        
        # Escribimos el contenido actualizado
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(updated_content)
        
        print(f"API key actualizada exitosamente en {file_path}")
        return True
    
    except Exception as e:
        print(f"Error al actualizar la API key: {str(e)}")
        return False

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Uso: python update_api_key.py <tu-api-key>")
        sys.exit(1)
    
    api_key = sys.argv[1]
    if update_api_key(api_key):
        print("Ahora puedes reiniciar el servidor de Django con 'python manage.py runserver'")
    else:
        print("No se pudo actualizar la API key.")
