#!/usr/bin/env python3
"""Drop all tables from the web database to start fresh."""

import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import inspect
from backend.db.session import engine, get_database_url
from backend.db.models import Base

# Ordered list ensures foreign-key dependents drop first
TARGET_TABLES = [
    "photo_favorites",
    "phototaglinkage",
    "person_encodings",
    "faces",
    "tags",
    "photos",
    "people",
]


def drop_all_tables():
    """Drop all tables from the database."""
    db_url = get_database_url()
    print(f"Connecting to database: {db_url}")
    
    inspector = inspect(engine)
    existing_tables = set(inspector.get_table_names())
    
    print("\nDropping selected tables...")
    for table_name in TARGET_TABLES:
        if table_name not in Base.metadata.tables:
            print(f"  ⚠️  Table '{table_name}' not found in metadata, skipping.")
            continue
        if table_name not in existing_tables:
            print(f"  ℹ️  Table '{table_name}' does not exist in database, skipping.")
            continue
        table = Base.metadata.tables[table_name]
        print(f"  🗑️  Dropping '{table_name}'...")
        table.drop(bind=engine, checkfirst=True)
    
    print("✅ Selected tables dropped successfully!")
    print("\nYou can now recreate tables using:")
    print("  python scripts/recreate_tables_web.py")


if __name__ == "__main__":
    try:
        drop_all_tables()
    except Exception as e:
        print(f"❌ Error dropping tables: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

