import os
import sys
from sqlmodel import Session, select, create_engine, inspect

# Add root directory to sys.path
sys.path.append(os.getcwd())

from app.database import engine
from app.models.auth import UserTable
from app.models.watchlist import WatchlistItemTable, WatchlistSettingsTable
from app.models.favorites import FavoriteTable
from app.models.sonarr import SonarrMappingTable, SonarrConfigTable

def audit_db():
    print("--- Ohm Stream Downloader: SQL Database Audit ---")
    
    if not os.path.exists("ohm_streaming.db"):
        print("ERROR: ohm_streaming.db not found!")
        return

    inspector = inspect(engine)
    tables = inspector.get_table_names()
    print(f"Tables found: {', '.join(tables)}")
    
    expected_tables = ["users", "watchlist_items", "watchlist_settings", "favorites", "sonarr_mappings", "sonarr_config", "alembic_version"]
    missing = [t for t in expected_tables if t not in tables]
    if missing:
        print(f"WARNING: Missing tables: {', '.join(missing)}")
    else:
        print("SUCCESS: All core tables are present.")

    with Session(engine) as session:
        # Check users
        users_count = len(session.exec(select(UserTable)).all())
        print(f"Users: {users_count}")
        
        # Check watchlist
        watchlist_count = len(session.exec(select(WatchlistItemTable)).all())
        print(f"Watchlist Items: {watchlist_count}")
        
        # Check settings
        settings_count = len(session.exec(select(WatchlistSettingsTable)).all())
        print(f"Watchlist Settings entries: {settings_count}")
        
        # Check favorites
        fav_count = len(session.exec(select(FavoriteTable)).all())
        print(f"Favorites: {fav_count}")
        
        # Check Sonarr
        sonarr_map_count = len(session.exec(select(SonarrMappingTable)).all())
        print(f"Sonarr Mappings: {sonarr_map_count}")
        
        # Sample data check
        if fav_count > 0:
            sample_fav = session.exec(select(FavoriteTable).limit(1)).first()
            print(f"Sample Favorite: {sample_fav.title} ({sample_fav.provider})")

if __name__ == "__main__":
    audit_db()
