#!/bin/bash

# HotTrend Tees 原型快速启动脚本
# 使用方法: bash quick_start.sh

set -e

echo "🚀 HotTrend Tees 原型快速启动"
echo "================================"

# 检查必要的工具
check_dependencies() {
    echo "📋 检查依赖项..."
    
    if ! command -v docker &> /dev/null; then
        echo "❌ Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v node &> /dev/null; then
        echo "❌ Node.js 未安装，请先安装 Node.js"
        exit 1
    fi
    
    if ! command -v python3 &> /dev/null; then
        echo "❌ Python3 未安装，请先安装 Python3"
        exit 1
    fi
    
    echo "✅ 依赖项检查完成"
}

# 创建项目目录结构
setup_project_structure() {
    echo "📁 创建项目目录结构..."
    
    mkdir -p hottrend-tees/{backend,frontend,docker,scripts,docs}
    mkdir -p hottrend-tees/backend/{app/{models,services,api,utils},tests}
    mkdir -p hottrend-tees/frontend/{src/{components,services},public}
    
    cd hottrend-tees
    echo "✅ 项目结构创建完成"
}

# 创建环境配置文件
create_env_files() {
    echo "⚙️ 创建环境配置文件..."
    
    # 后端环境配置
    cat > backend/.env.example << 'EOF'
# Twitter API 配置
TWITTER_BEARER_TOKEN=your_twitter_bearer_token
TWITTER_API_KEY=your_twitter_api_key
TWITTER_API_SECRET=your_twitter_api_secret
TWITTER_ACCESS_TOKEN=your_twitter_access_token
TWITTER_ACCESS_TOKEN_SECRET=your_twitter_access_token_secret

# OpenAI API 配置
OPENAI_API_KEY=your_openai_api_key

# AWS 配置
AWS_ACCESS_KEY_ID=your_aws_access_key
AWS_SECRET_ACCESS_KEY=your_aws_secret_key
AWS_REGION=us-east-1
AWS_S3_BUCKET=hottrend-tees-designs

# 数据库配置
DATABASE_URL=postgresql://user:password@localhost/hottrend_tees

# Redis 配置
REDIS_URL=redis://localhost:6379
EOF

    # 前端环境配置
    cat > frontend/.env.example << 'EOF'
REACT_APP_API_URL=http://localhost:8000
REACT_APP_APP_NAME=HotTrend Tees
EOF

    echo "✅ 环境配置文件创建完成"
    echo "⚠️  请复制 .env.example 为 .env 并填入真实的API密钥"
}

# 创建Docker配置
create_docker_configs() {
    echo "🐳 创建Docker配置..."
    
    # 后端Dockerfile
    cat > backend/Dockerfile << 'EOF'
FROM python:3.11-slim

WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# 安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

EXPOSE 8000

# 启动应用
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
EOF

    # 前端Dockerfile
    cat > frontend/Dockerfile << 'EOF'
FROM node:18-alpine AS build

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
EOF

    # Nginx配置
    cat > frontend/nginx.conf << 'EOF'
events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server {
        listen 80;
        server_name localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        location /api/ {
            proxy_pass http://backend:8000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}
EOF

    # Docker Compose配置
    cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  backend:
    build: ./backend
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://postgres:password@db:5432/hottrend_tees
      - REDIS_URL=redis://redis:6379
    env_file:
      - ./backend/.env
    depends_on:
      - db
      - redis
    volumes:
      - ./backend:/app
    restart: unless-stopped

  frontend:
    build: ./frontend
    ports:
      - "3000:80"
    depends_on:
      - backend
    restart: unless-stopped

  db:
    image: postgres:15
    environment:
      POSTGRES_DB: hottrend_tees
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:
EOF

    echo "✅ Docker配置创建完成"
}

# 创建package.json文件
create_package_files() {
    echo "📦 创建package.json文件..."
    
    # 后端requirements.txt
    cat > backend/requirements.txt << 'EOF'
fastapi==0.104.1
uvicorn[standard]==0.24.0
tweepy==4.14.0
openai==1.3.7
boto3==1.29.7
sqlalchemy==2.0.23
psycopg2-binary==2.9.9
redis==5.0.1
celery==5.3.4
python-multipart==0.0.6
python-dotenv==1.0.0
requests==2.31.0
pillow==10.1.0
pydantic-settings==2.1.0
alembic==1.13.1
asyncpg==0.29.0
aiohttp==3.9.1
pytest==7.4.3
pytest-asyncio==0.21.1
httpx==0.25.2
EOF

    # 前端package.json
    cat > frontend/package.json << 'EOF'
{
  "name": "hottrend-tees-frontend",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "@mui/icons-material": "^5.14.19",
    "@mui/material": "^5.14.20",
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.6.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.8.0",
    "react-scripts": "5.0.1",
    "recharts": "^2.8.0",
    "styled-components": "^6.1.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8000"
}
EOF

    echo "✅ Package文件创建完成"
}

# 创建基础代码文件
create_basic_code() {
    echo "💻 创建基础代码文件..."
    
    # 后端主文件
    cat > backend/app/__init__.py << 'EOF'
# HotTrend Tees Backend
EOF

    cat > backend/app/main.py << 'EOF'
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(
    title="HotTrend Tees API",
    description="AI驱动的T-shirt定制平台原型API",
    version="1.0.0"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"message": "HotTrend Tees API v1.0.0", "status": "running"}

@app.get("/api/health")
async def health_check():
    return {
        "status": "healthy",
        "timestamp": "2025-07-03T00:00:00Z",
        "services": {
            "api": "running"
        }
    }
EOF

    # 前端基础文件
    cat > frontend/public/index.html << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="HotTrend Tees - AI驱动的T-shirt定制平台" />
    <title>HotTrend Tees</title>
  </head>
  <body>
    <noscript>您需要启用JavaScript才能运行此应用程序。</noscript>
    <div id="root"></div>
  </body>
</html>
EOF

    cat > frontend/src/index.js << 'EOF'
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
EOF

    cat > frontend/src/App.js << 'EOF'
import React, { useState, useEffect } from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import {
  CssBaseline,
  AppBar,
  Toolbar,
  Typography,
  Container,
  Box,
  Card,
  CardContent,
  Button,
  Alert
} from '@mui/material';
import { AutoAwesome } from '@mui/icons-material';

const theme = createTheme({
  palette: {
    primary: {
      main: '#6366f1',
    },
    secondary: {
      main: '#ec4899',
    },
  },
});

function App() {
  const [apiStatus, setApiStatus] = useState('checking');

  useEffect(() => {
    checkApiHealth();
  }, []);

  const checkApiHealth = async () => {
    try {
      const response = await fetch('/api/health');
      const data = await response.json();
      setApiStatus(data.status === 'healthy' ? 'healthy' : 'error');
    } catch (error) {
      setApiStatus('error');
    }
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      
      <AppBar position="static" elevation={0}>
        <Toolbar>
          <AutoAwesome sx={{ mr: 2 }} />
          <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
            HotTrend Tees - AI驱动的T-shirt定制平台
          </Typography>
        </Toolbar>
      </AppBar>

      <Container maxWidth="md" sx={{ py: 4 }}>
        <Box textAlign="center" mb={4}>
          <Typography variant="h3" component="h1" gutterBottom>
            欢迎使用 HotTrend Tees 原型
          </Typography>
          <Typography variant="h6" color="textSecondary" paragraph>
            基于 Twitter API v2 + OpenAI + AWS 的AI驱动T-shirt定制平台
          </Typography>
        </Box>

        <Card sx={{ mb: 4 }}>
          <CardContent>
            <Typography variant="h5" gutterBottom>
              系统状态
            </Typography>
            
            {apiStatus === 'checking' && (
              <Alert severity="info">正在检查API连接...</Alert>
            )}
            
            {apiStatus === 'healthy' && (
              <Alert severity="success">API服务运行正常</Alert>
            )}
            
            {apiStatus === 'error' && (
              <Alert severity="error" action={
                <Button color="inherit" size="small" onClick={checkApiHealth}>
                  重试
                </Button>
              }>
                API服务连接失败
              </Alert>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Typography variant="h5" gutterBottom>
              下一步操作
            </Typography>
            <Typography paragraph>
              1. 配置API密钥（Twitter、OpenAI、AWS）
            </Typography>
            <Typography paragraph>
              2. 启动完整功能模块
            </Typography>
            <Typography paragraph>
              3. 测试趋势分析和设计生成功能
            </Typography>
            
            <Button 
              variant="contained" 
              size="large" 
              sx={{ mt: 2 }}
              onClick={() => window.open('/api/docs', '_blank')}
            >
              查看API文档
            </Button>
          </CardContent>
        </Card>
      </Container>
    </ThemeProvider>
  );
}

export default App;
EOF

    echo "✅ 基础代码文件创建完成"
}

# 创建启动脚本
create_startup_scripts() {
    echo "🔧 创建启动脚本..."
    
    # 开发环境启动脚本
    cat > scripts/start-dev.sh << 'EOF'
#!/bin/bash

echo "🚀 启动HotTrend Tees开发环境"

# 检查环境文件
if [ ! -f "./backend/.env" ]; then
    echo "❌ 请先创建 backend/.env 文件"
    echo "💡 提示: 复制 backend/.env.example 为 backend/.env 并填入API密钥"
    exit 1
fi

if [ ! -f "./frontend/.env" ]; then
    echo "❌ 请先创建 frontend/.env 文件"
    echo "💡 提示: 复制 frontend/.env.example 为 frontend/.env"
    exit 1
fi

# 启动服务
echo "🐳 启动Docker服务..."
docker-compose up -d db redis

echo "⏳ 等待数据库启动..."
sleep 10

echo "🐍 启动后端服务..."
cd backend
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 &
cd ..

echo "⚛️ 启动前端服务..."
cd frontend
npm install
npm start &
cd ..

echo "✅ 开发环境启动完成!"
echo "🌐 前端地址: http://localhost:3000"
echo "📡 后端API: http://localhost:8000"
echo "📚 API文档: http://localhost:8000/docs"
EOF

    # 生产环境启动脚本
    cat > scripts/start-prod.sh << 'EOF'
#!/bin/bash

echo "🚀 启动HotTrend Tees生产环境"

# 检查环境文件
if [ ! -f "./backend/.env" ]; then
    echo "❌ 请先创建 backend/.env 文件"
    exit 1
fi

if [ ! -f "./frontend/.env" ]; then
    echo "❌ 请先创建 frontend/.env 文件"
    exit 1
fi

# 构建并启动所有服务
echo "🐳 构建并启动所有服务..."
docker-compose up -d --build

echo "⏳ 等待服务启动..."
sleep 30

echo "✅ 生产环境启动完成!"
echo "🌐 应用地址: http://localhost:3000"
echo "📡 API地址: http://localhost:8000"

# 显示服务状态
docker-compose ps
EOF

    # 停止脚本
    cat > scripts/stop.sh << 'EOF'
#!/bin/bash

echo "🛑 停止HotTrend Tees服务"

# 停止Docker服务
docker-compose down

# 停止本地进程
pkill -f "uvicorn app.main:app"
pkill -f "npm start"

echo "✅ 所有服务已停止"
EOF

    # 设置脚本可执行权限
    chmod +x scripts/*.sh

    echo "✅ 启动脚本创建完成"
}

# 创建测试脚本
create_test_script() {
    echo "🧪 创建测试脚本..."
    
    cat > scripts/test-api.py << 'EOF'
#!/usr/bin/env python3

import asyncio
import aiohttp
import json
import sys

async def test_api():
    base_url = "http://localhost:8000"
    
    print("🧪 开始API测试")
    print("=" * 40)
    
    async with aiohttp.ClientSession() as session:
        try:
            # 测试健康检查
            print("📋 测试健康检查...")
            async with session.get(f"{base_url}/api/health") as resp:
                if resp.status == 200:
                    health_data = await resp.json()
                    print(f"✅ 健康检查通过: {health_data['status']}")
                else:
                    print(f"❌ 健康检查失败: HTTP {resp.status}")
                    return False
            
            # 测试根路径
            print("🏠 测试根路径...")
            async with session.get(f"{base_url}/") as resp:
                if resp.status == 200:
                    root_data = await resp.json()
                    print(f"✅ 根路径访问成功: {root_data['message']}")
                else:
                    print(f"❌ 根路径访问失败: HTTP {resp.status}")
                    return False
            
            print("\n🎉 所有基础测试通过!")
            print("💡 提示: 配置API密钥后可以测试完整功能")
            return True
            
        except aiohttp.ClientError as e:
            print(f"❌ 连接失败: {e}")
            print("💡 确保后端服务已启动 (python -m uvicorn app.main:app)")
            return False
        except Exception as e:
            print(f"❌ 测试失败: {e}")
            return False

if __name__ == "__main__":
    success = asyncio.run(test_api())
    sys.exit(0 if success else 1)
EOF

    chmod +x scripts/test-api.py
    
    echo "✅ 测试脚本创建完成"
}

# 创建README文件
create_readme() {
    echo "📖 创建README文件..."
    
    cat > README.md << 'EOF'
# HotTrend Tees 原型项目

🚀 基于 Twitter API v2 + OpenAI + AWS 的AI驱动T-shirt定制平台原型

## 快速开始

### 1. 环境准备

```bash
# 复制环境配置文件
cp backend/.env.example backend/.env
cp frontend/.env.example frontend/.env

# 编辑环境文件，填入真实的API密钥
# backend/.env - 填入Twitter、OpenAI、AWS密钥
# frontend/.env - 配置前端参数
```

### 2. 开发环境启动

```bash
# 启动开发环境
bash scripts/start-dev.sh

# 或分别启动各个组件
# 1. 启动数据库和Redis
docker-compose up -d db redis

# 2. 启动后端
cd backend
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
uvicorn app.main:app --reload

# 3. 启动前端
cd frontend
npm install
npm start
```

### 3. 生产环境部署

```bash
# 启动生产环境
bash scripts/start-prod.sh

# 或使用Docker Compose
docker-compose up -d --build
```

### 4. API测试

```bash
# 运行API测试
python scripts/test-api.py

# 或手动测试
curl http://localhost:8000/api/health
```

## 访问地址

- 🌐 前端应用: http://localhost:3000
- 📡 后端API: http://localhost:8000
- 📚 API文档: http://localhost:8000/docs
- 🗄️ 数据库: localhost:5432
- 🔴 Redis: localhost:6379

## 项目结构

```
hottrend-tees/
├── backend/               # FastAPI后端
│   ├── app/              # 应用代码
│   ├── requirements.txt   # Python依赖
│   └── Dockerfile        # Docker配置
├── frontend/             # React前端
│   ├── src/              # 源代码
│   ├── package.json      # Node依赖
│   └── Dockerfile        # Docker配置
├── scripts/              # 脚本文件
│   ├── start-dev.sh      # 开发环境启动
│   ├── start-prod.sh     # 生产环境启动
│   ├── stop.sh           # 停止服务
│   └── test-api.py       # API测试
├── docker-compose.yml    # Docker编排
└── README.md            # 项目说明
```

## 功能特性

### ✅ 已实现
- 基础API框架 (FastAPI)
- 前端界面框架 (React + Material-UI)
- Docker容器化部署
- 健康检查和监控
- 开发/生产环境配置

### 🚧 待实现 (需要API密钥)
- Twitter趋势数据获取
- OpenAI图像生成
- AWS S3存储集成
- 用户认证系统
- 订单管理系统

## 开发指南

### 环境要求
- Python 3.11+
- Node.js 18+
- Docker & Docker Compose
- PostgreSQL 15+
- Redis 7+

### API密钥配置

1. **Twitter API v2**
   - 访问: https://developer.twitter.com/
   - 申请开发者账号并创建应用
   - 获取Bearer Token和API密钥

2. **OpenAI API**
   - 访问: https://platform.openai.com/
   - 创建账号并生成API密钥
   - 确保账户有DALL-E 3访问权限

3. **AWS服务**
   - 访问: https://aws.amazon.com/
   - 创建IAM用户并配置S3权限
   - 获取Access Key和Secret Key

### 调试技巧

```bash
# 查看容器日志
docker-compose logs backend
docker-compose logs frontend

# 进入容器调试
docker-compose exec backend bash
docker-compose exec db psql -U postgres -d hottrend_tees

# 重启特定服务
docker-compose restart backend
```

## 部署指南

### AWS ECS部署

1. 构建Docker镜像
2. 推送到ECR
3. 创建ECS任务定义
4. 部署到ECS集群

详细部署步骤请参考: `docs/deployment.md`

## 贡献指南

1. Fork项目
2. 创建功能分支
3. 提交代码
4. 创建Pull Request

## 许可证

MIT License

## 支持

如有问题，请创建Issue或联系开发团队。
EOF
    
    echo "✅ README文件创建完成"
}

# 显示完成信息
show_completion_info() {
    echo ""
    echo "🎉 HotTrend Tees 原型项目创建完成!"
    echo "================================"
    echo ""
    echo "📁 项目位置: $(pwd)"
    echo ""
    echo "📋 下一步操作:"
    echo "1️⃣  配置API密钥:"
    echo "   cp backend/.env.example backend/.env"
    echo "   cp frontend/.env.example frontend/.env"
    echo "   # 编辑 .env 文件，填入真实的API密钥"
    echo ""
    echo "2️⃣  启动开发环境:"
    echo "   bash scripts/start-dev.sh"
    echo ""
    echo "3️⃣  访问应用:"
    echo "   🌐 前端: http://localhost:3000"
    echo "   📡 API: http://localhost:8000"
    echo "   📚 文档: http://localhost:8000/docs"
    echo ""
    echo "4️⃣  运行测试:"
    echo "   python scripts/test-api.py"
    echo ""
    echo "📖 更多信息请查看 README.md 文件"
    echo ""
}

# 主执行流程
main() {
    echo "开始创建 HotTrend Tees 原型项目..."
    
    check_dependencies
    setup_project_structure
    create_env_files
    create_docker_configs
    create_package_files
    create_basic_code
    create_startup_scripts
    create_test_script
    create_readme
    
    show_completion_info
}

# 运行主函数
main "$@"
