#!/bin/bash

# Memory Bank Web界面启动脚本
# 自动设置环境并启动Streamlit应用

echo "🧠 启动Memory Bank Web界面..."
echo "================================"

# 检查是否在正确的目录
if [ ! -f "memory_bank_web_interface.py" ]; then
    echo "❌ 错误: 未找到memory_bank_web_interface.py文件"
    echo "请确保在正确的项目目录中运行此脚本"
    exit 1
fi

# 检查虚拟环境
if [ ! -d "venv" ]; then
    echo "📦 创建虚拟环境..."
    python3 -m venv venv
fi

# 激活虚拟环境
echo "🔧 激活虚拟环境..."
source venv/bin/activate

# 检查并安装依赖
echo "📋 检查依赖包..."

# 检查streamlit
if ! python -c "import streamlit" 2>/dev/null; then
    echo "📦 安装Streamlit..."
    pip install streamlit
fi

# 检查Google Cloud依赖
if ! python -c "import google.cloud" 2>/dev/null; then
    echo "📦 安装Google Cloud依赖..."
    pip install google-cloud-aiplatform google-generativeai
fi

# 检查其他必要依赖
if ! python -c "import asyncio" 2>/dev/null; then
    echo "📦 安装asyncio依赖..."
    pip install asyncio
fi

# 检查Google Cloud认证
echo "🔐 检查Google Cloud认证..."
if ! gcloud auth application-default print-access-token >/dev/null 2>&1; then
    echo "⚠️  未检测到Google Cloud认证"
    echo "正在启动认证流程..."
    gcloud auth application-default login
fi

# 设置环境变量
export GOOGLE_CLOUD_PROJECT="inner-radius-469712-e9"
export GOOGLE_CLOUD_REGION="us-central1"

# 启动Streamlit应用
echo "🚀 启动Web界面..."
echo "================================"
echo "📱 Web界面将在浏览器中打开"
echo "🌐 默认地址: http://localhost:8501"
echo "⏹️  按 Ctrl+C 停止服务"
echo "================================"

# 启动streamlit
streamlit run memory_bank_web_interface.py --server.port 8501 --server.address localhost