# DramaLing 開發環境初始設置指南

## 前置需求

### 必要軟體
- Node.js 18+ (建議使用 nvm 管理版本)
- Git
- VS Code 或其他程式碼編輯器

### 必要帳號
- GitHub 帳號
- Supabase 帳號
- Vercel 帳號
- Google Cloud Platform 帳號（for Gemini API）

## 步驟 1: 克隆專案

```bash
git clone [your-repo-url]
cd dramaling-vocab-learning
```

## 步驟 2: 安裝依賴

```bash
# 安裝專案依賴
npm install

# 安裝 shadcn/ui CLI
npx shadcn-ui@latest init
```

shadcn/ui 設定選項：
- Would you like to use TypeScript? → Yes
- Which style would you like to use? → Default
- Which color would you like to use as base color? → Slate
- Where is your global CSS file? → src/app/globals.css
- Would you like to use CSS variables for colors? → Yes
- Where is your tailwind.config.js located? → tailwind.config.ts
- Configure the import alias for components? → @/components
- Configure the import alias for utils? → @/lib/utils

## 步驟 3: 設置 Supabase

### 3.1 建立新專案
1. 前往 [Supabase Dashboard](https://app.supabase.com)
2. 點擊 "New Project"
3. 填寫專案資訊：
   - Project name: dramaling-vocab
   - Database Password: (記住此密碼)
   - Region: 選擇最近的區域

### 3.2 取得 API Keys
在專案設定中找到：
- Project URL
- Anon/Public Key
- Service Role Key (保密)

### 3.3 設置資料庫
執行以下 SQL 在 Supabase SQL Editor：

```sql
-- Enable UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Create profiles table
CREATE TABLE profiles (
  id UUID REFERENCES auth.users ON DELETE CASCADE PRIMARY KEY,
  email TEXT UNIQUE,
  username TEXT,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW())
);

-- Create flashcards table
CREATE TABLE flashcards (
  id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
  user_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
  word VARCHAR(255) NOT NULL,
  translation TEXT,
  context TEXT,
  example TEXT,
  pronunciation TEXT,
  difficulty INTEGER DEFAULT 3,
  next_review_date DATE DEFAULT CURRENT_DATE,
  review_count INTEGER DEFAULT 0,
  ease_factor DECIMAL(3,2) DEFAULT 2.5,
  interval INTEGER DEFAULT 1,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW())
);

-- Create study_sessions table
CREATE TABLE study_sessions (
  id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
  user_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
  flashcard_id UUID REFERENCES flashcards(id) ON DELETE CASCADE,
  rating INTEGER CHECK (rating >= 1 AND rating <= 5),
  studied_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW())
);

-- Create tags table
CREATE TABLE tags (
  id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  user_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()),
  UNIQUE(name, user_id)
);

-- Create flashcard_tags junction table
CREATE TABLE flashcard_tags (
  flashcard_id UUID REFERENCES flashcards(id) ON DELETE CASCADE,
  tag_id UUID REFERENCES tags(id) ON DELETE CASCADE,
  PRIMARY KEY (flashcard_id, tag_id)
);

-- Set up Row Level Security (RLS)
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE flashcards ENABLE ROW LEVEL SECURITY;
ALTER TABLE study_sessions ENABLE ROW LEVEL SECURITY;
ALTER TABLE tags ENABLE ROW LEVEL SECURITY;
ALTER TABLE flashcard_tags ENABLE ROW LEVEL SECURITY;

-- Create policies
CREATE POLICY "Users can view own profile" ON profiles
  FOR SELECT USING (auth.uid() = id);

CREATE POLICY "Users can update own profile" ON profiles
  FOR UPDATE USING (auth.uid() = id);

CREATE POLICY "Users can view own flashcards" ON flashcards
  FOR SELECT USING (auth.uid() = user_id);

CREATE POLICY "Users can create own flashcards" ON flashcards
  FOR INSERT WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can update own flashcards" ON flashcards
  FOR UPDATE USING (auth.uid() = user_id);

CREATE POLICY "Users can delete own flashcards" ON flashcards
  FOR DELETE USING (auth.uid() = user_id);

-- Create functions
CREATE OR REPLACE FUNCTION handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO public.profiles (id, email)
  VALUES (new.id, new.email);
  RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Create trigger for new user
CREATE TRIGGER on_auth_user_created
  AFTER INSERT ON auth.users
  FOR EACH ROW EXECUTE FUNCTION handle_new_user();
```

## 步驟 4: 設置 Gemini API

1. 前往 [Google AI Studio](https://makersuite.google.com/app/apikey)
2. 點擊 "Create API Key"
3. 複製 API Key

## 步驟 5: 環境變數設置

建立 `.env.local` 檔案：

```env
# Supabase
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key

# Gemini AI
GEMINI_API_KEY=your_gemini_api_key

# App
NEXT_PUBLIC_APP_URL=http://localhost:3000
```

## 步驟 6: 啟動開發伺服器

```bash
npm run dev
```

訪問 http://localhost:3000 查看應用

## 步驟 7: 安裝推薦的 VS Code 擴展

- ESLint
- Prettier
- Tailwind CSS IntelliSense
- TypeScript and JavaScript Language Features
- Prisma (如果使用 Prisma)

## 常見問題

### 1. Supabase 連接錯誤
- 檢查環境變數是否正確
- 確認 Supabase 專案是否啟動
- 檢查 RLS 政策是否正確設置

### 2. Gemini API 錯誤
- 確認 API Key 是否有效
- 檢查配額限制
- 確認網路連接

### 3. Build 錯誤
- 清除 .next 資料夾：`rm -rf .next`
- 清除 node_modules：`rm -rf node_modules && npm install`
- 檢查 TypeScript 錯誤：`npm run type-check`

## 下一步

完成初始設置後，請參考：
1. [Week 1 實作指南](../implementation/week1-auth.md) - 開始實作認證系統
2. [API 文檔](../api/supabase-schema.md) - 了解資料庫架構
3. [開發指南](./dependencies.md) - 了解專案依賴