# Phase 1 Database Migration Instructions

This document explains how to set up the Phase 1 Daily Helper database tables.

## Option 1: Using the Migration Script (Recommended - No Alembic Required)

```bash
cd backend
python create_phase1_tables.py
```

This will create all 6 Phase 1 tables in your database:
- `user_profiles`
- `daily_routines`
- `routine_executions`
- `notifications`
- `daily_checklists`
- `habit_trackers`

### What the script does:
1. Connects to your database using the configured URL
2. Creates all tables defined in the models
3. Verifies that tables were created successfully

## Option 2: Using Alembic (If You Have It Set Up)

If you're using Alembic for migrations:

```bash
cd backend
alembic revision --autogenerate -m "Add Phase 1 daily helper models"
alembic upgrade head
```

## Option 3: Manual SQL

If you need to create tables manually, here's the SQL:

### user_profiles
```sql
CREATE TABLE user_profiles (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email VARCHAR UNIQUE,
    username VARCHAR UNIQUE,
    timezone VARCHAR DEFAULT 'UTC',
    preferred_trading_start VARCHAR DEFAULT '09:00',
    preferred_trading_end VARCHAR DEFAULT '17:00',
    risk_tolerance VARCHAR DEFAULT 'moderate',
    trading_style VARCHAR DEFAULT 'day_trader',
    daily_target FLOAT,
    max_loss FLOAT,
    notifications_enabled BOOLEAN DEFAULT true,
    email_reports BOOLEAN DEFAULT true,
    sms_enabled BOOLEAN DEFAULT false,
    push_notifications BOOLEAN DEFAULT true,
    phone_number VARCHAR,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

### daily_routines
```sql
CREATE TABLE daily_routines (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id VARCHAR,
    routine_type VARCHAR,
    scheduled_time VARCHAR,
    tasks JSON DEFAULT '[]',
    enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

### routine_executions
```sql
CREATE TABLE routine_executions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    routine_id INTEGER,
    executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completion_status VARCHAR,
    tasks_completed JSON DEFAULT '[]',
    execution_notes TEXT,
    FOREIGN KEY (routine_id) REFERENCES daily_routines(id)
);
```

### notifications
```sql
CREATE TABLE notifications (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id VARCHAR,
    notification_type VARCHAR,
    title VARCHAR,
    message TEXT,
    priority VARCHAR DEFAULT 'normal',
    delivery_method VARCHAR DEFAULT 'push',
    data JSON,
    read BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    read_at TIMESTAMP
);
```

### daily_checklists
```sql
CREATE TABLE daily_checklists (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id VARCHAR,
    checklist_date DATE DEFAULT CURRENT_DATE,
    checklist_type VARCHAR,
    items JSON DEFAULT '[]',
    completion_percentage FLOAT DEFAULT 0.0,
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

### habit_trackers
```sql
CREATE TABLE habit_trackers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id VARCHAR,
    habit_name VARCHAR,
    frequency VARCHAR,
    completion_dates JSON DEFAULT '[]',
    current_streak INTEGER DEFAULT 0,
    longest_streak INTEGER DEFAULT 0,
    total_completions INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## Verification

After running the migration, verify the tables exist:

```bash
# Using Python
python -c "from app.db.database import engine; print(engine.table_names())"

# Or check your database directly
# SQLite: sqlite3 your_database.db ".tables"
# PostgreSQL: psql -l
# MySQL: mysql -e "SHOW TABLES;"
```

## Troubleshooting

### Error: "No module named 'app'"
Make sure you're running the script from the `backend` directory and have activated your Python virtual environment.

### Error: "database is locked"
If using SQLite, close any other applications accessing the database.

### Error: "Connection refused"
Make sure your database server is running (PostgreSQL, MySQL, etc.)

### Tables already exist
If tables already exist, the script will update their structure if needed. Existing data will be preserved.

## Rollback (If Needed)

If you need to remove the tables:

```bash
# Using Python
python -c "from app.db.database import engine, Base; from app.models.models import *; Base.metadata.drop_all(bind=engine)"

# Or manually drop tables in your database
DROP TABLE habit_trackers;
DROP TABLE daily_checklists;
DROP TABLE notifications;
DROP TABLE routine_executions;
DROP TABLE daily_routines;
DROP TABLE user_profiles;
```

## Next Steps

After creating the tables:

1. **Initialize a User Profile:**
   ```bash
   curl -X POST http://localhost:8000/api/daily-helper/profile \
     -H "Content-Type: application/json" \
     -d '{
       "email": "trader@example.com",
       "timezone": "EST",
       "trading_style": "day_trader",
       "risk_tolerance": "moderate"
     }'
   ```

2. **Create a Daily Routine:**
   ```bash
   curl -X POST http://localhost:8000/api/daily-helper/routines \
     -H "Content-Type: application/json" \
     -d '{
       "routine_type": "morning",
       "scheduled_time": "08:30",
       "tasks": ["market_brief", "checklist", "review_plan"],
       "enabled": true
     }'
   ```

3. **Test the API:**
   Visit `http://localhost:8000/docs` to access the Swagger UI and test endpoints.

4. **Integrate Frontend:**
   Import Phase 1 components in your `App.tsx` (see FRONTEND_INTEGRATION.md)

---

For more information, see:
- `PHASE1_IMPLEMENTATION_SUMMARY.md` - Detailed implementation overview
- `DAILY_HELPER_ENHANCEMENT_PLAN.md` - Full enhancement roadmap
