import os, sqlite3
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tianxuan.settings')

application = get_wsgi_application()

# ── Auto-migrate on fresh DB ──────────────────────────────────────
# A brand-new database has zero tables — migrate + import tls_ref_data.
from django.db import connection
from django.core.management import call_command
with connection.cursor() as cursor:
    cursor.execute("SELECT count(*) FROM sqlite_master WHERE type='table'")
    if cursor.fetchone()[0] == 0:
        call_command('migrate')
        call_command('import_tlsdb')

# ── DB integrity check ────────────────────────────────────────────
# Uses settings DB path (may be %APPDATA%/TianXuan/db.sqlite3)
from django.conf import settings
db_path = settings.DATABASES['default']['NAME']
if os.path.exists(db_path):
    try:
        conn = sqlite3.connect(str(db_path))
        conn.execute('PRAGMA integrity_check')
        conn.close()
    except Exception:
        import shutil, time
        from django.core.management import call_command
        backup = str(db_path) + f'.corrupted.{int(time.time())}'
        shutil.copy2(str(db_path), str(backup))
        os.remove(db_path)
        call_command('migrate')
        # Also ensure tls_ref_data table exists after fresh migration
        try:
            call_command('import_tlsdb')
        except Exception:
            pass  # Expected: import_tlsdb may not exist as a management command
# Restore previously uploaded datasets whose CSV files still exist.
try:
    from analysis.session_store import SessionStore
    count = SessionStore().restore_from_disk()
    if count > 0:
        import logging
        logging.getLogger('django').info('Restored %d datasets from disk', count)
except Exception:
    pass  # Expected: session store may not be available on fresh install

# ── ensure tls_ref_data table ────────────────────────────────────
# Newly created databases won't have this table yet.
try:
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("SELECT 1 FROM tls_ref_data LIMIT 1")
except Exception:
    # Table doesn't exist — import it
    try:
        from django.core.management import call_command
        call_command('import_tlsdb')
    except Exception:
        pass  # Expected: tls_ref_data import may fail if reference data unavailable
