# test_migrace.py
import sys
import os

# Simulace spusteni v rootu pluginu
sys.path.append(os.path.dirname(__file__))

# Import zmigrované metadata_db (s fallback pathem na ~/.kodi_mmirousek_v3)
from resources.lib.database.metadata_db import db

def run_tests():
    import resources.lib.database.metadata_db as metadata_db
    if metadata_db.db.conn:
        metadata_db.db.conn.close()
    if os.path.exists(metadata_db.DB_PATH):
        try:
            os.remove(metadata_db.DB_PATH)
        except:
            pass
    # Znovu vytvořit spojení a tabulky aby se inicializovalo nové schéma
    metadata_db.db = metadata_db.MetadataDB()
    db = metadata_db.db
    print("Test: Připojení k DB...")
    if not db.conn:
        print("CHYBA: db.conn je None. Databáze se nevytvořila.")
        return

    print("Test: Tabulky (media, local_history)...")
    cur = db.conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = [row[0] for row in cur.fetchall()]
    print(f"Tabulky nalezene: {tables}")
    
    assert 'media' in tables, "Tabulka 'media' chybí!"
    assert 'local_history' in tables, "Tabulka 'local_history' chybí!"
    assert 'search_history' in tables, "Tabulka 'search_history' chybí!"
    assert 'episodes' in tables, "Tabulka 'episodes' chybí!"
    
    # Test vložení do historie
    item = {
        'tmdb_id': 12345,
        'media_type': 'movie',
        'title': 'Testovaci Film',
        'stream_url': 'http://test.url'
    }
    # Vlozeni
    try:
        print("Test: Vkladam do local_history...")
        db.save_local_history(**item)
        print("  OK")
    except Exception as e:
        print(f"  Vkladaní selhalo:")
        import traceback
        traceback.print_exc()

    print("Test: Vse OK! (Konec scriptu)")

if __name__ == '__main__':
    run_tests()
