"""
Database Migration: Add WhatsApp Message Tracking
==================================================

This migration adds the whatsapp_messages table for tracking
message delivery status from Meta WhatsApp Cloud API webhooks.

Run this migration:
    python add_whatsapp_messages_table.py
"""

import sys
from pathlib import Path

# Add backend to path
sys.path.insert(0, str(Path(__file__).parent))

from database import engine, Base, SessionLocal
from models import WhatsAppMessage
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def run_migration():
    """Create the whatsapp_messages table"""
    logger.info("Starting migration: Add whatsapp_messages table")
    
    try:
        # Create only the WhatsAppMessage table
        logger.info("Creating whatsapp_messages table...")
        WhatsAppMessage.__table__.create(engine, checkfirst=True)
        logger.info("✓ whatsapp_messages table created successfully")
        
        # Verify table exists
        db = SessionLocal()
        try:
            result = db.execute("SELECT COUNT(*) FROM whatsapp_messages")
            count = result.scalar()
            logger.info(f"✓ Table verified: {count} messages in database")
        finally:
            db.close()
        
        logger.info("Migration completed successfully!")
        
    except Exception as e:
        logger.error(f"✗ Migration failed: {e}")
        raise


if __name__ == "__main__":
    print("="*80)
    print("WhatsApp Messages Table Migration")
    print("="*80)
    print("\nThis will create the whatsapp_messages table for tracking")
    print("delivery status of WhatsApp messages sent through Meta Cloud API.")
    print()
    
    response = input("Proceed with migration? (yes/no): ").strip().lower()
    if response in ['yes', 'y']:
        run_migration()
    else:
        print("Migration cancelled.")
