#!/usr/bin/env python3
"""
Database migration script for Phase 1 Daily Helper models
Run this script to create all necessary tables in your database

Usage:
    python create_phase1_tables.py
"""

import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Import database configuration and models
from app.db.database import SQLALCHEMY_DATABASE_URL, Base
from app.models.models import (
    UserProfile, DailyRoutine, RoutineExecution, Notification,
    DailyChecklist, HabitTracker
)


def create_tables():
    """Create all Phase 1 tables in the database"""
    print("🚀 Creating Phase 1 Daily Helper tables...")

    try:
        # Create database engine
        engine = create_engine(
            SQLALCHEMY_DATABASE_URL,
            echo=True  # Print SQL statements
        )

        # Create all tables defined in Base.metadata
        print("\n📦 Creating tables...")
        Base.metadata.create_all(bind=engine)

        print("\n✅ Tables created successfully!")
        print("\nCreated tables:")
        print("  1. user_profiles - User preferences and settings")
        print("  2. daily_routines - Scheduled daily routines")
        print("  3. routine_executions - Routine execution history")
        print("  4. notifications - System notifications")
        print("  5. daily_checklists - Daily task checklists")
        print("  6. habit_trackers - Habit tracking with streaks")

        # Verify tables were created
        inspector_tables = engine.inspect(engine).get_table_names()
        phase1_tables = [
            'user_profiles', 'daily_routines', 'routine_executions',
            'notifications', 'daily_checklists', 'habit_trackers'
        ]

        created = [t for t in phase1_tables if t in inspector_tables]
        print(f"\n📊 Verification: {len(created)}/{len(phase1_tables)} tables created")

        if len(created) == len(phase1_tables):
            print("✨ All Phase 1 tables are ready!")
            return True
        else:
            missing = [t for t in phase1_tables if t not in inspector_tables]
            print(f"⚠️  Missing tables: {missing}")
            return False

    except Exception as e:
        print(f"\n❌ Error creating tables: {str(e)}")
        print("\nMake sure your database is running and accessible.")
        print(f"Database URL: {SQLALCHEMY_DATABASE_URL}")
        return False


if __name__ == "__main__":
    success = create_tables()
    sys.exit(0 if success else 1)
