
import os
from pathlib import Path

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

import django
django.setup()

from django.conf import settings
from django.db import connection
from django.db.migrations.loader import MigrationLoader

print("=== SKEVER PORTAL V1 READINESS CHECK ===")
print("Settings:", os.environ["DJANGO_SETTINGS_MODULE"])
print("Database engine:", settings.DATABASES["default"]["ENGINE"])
print("Database path:", settings.DATABASES["default"].get("NAME"))

try:
    connection.ensure_connection()
    print("\nDATABASE CONNECTION: OK")

    with connection.cursor() as cursor:
        cursor.execute("PRAGMA integrity_check")
        print("DATABASE INTEGRITY:", cursor.fetchone()[0])

        cursor.execute("""
            SELECT name
            FROM sqlite_master
            WHERE type = 'table'
            ORDER BY name
        """)
        tables = {row[0] for row in cursor.fetchall()}

    required_tables = {
        "auth_user",
        "django_migrations",
        "core_order",
        "core_customer",
        "core_payment",
        "core_dispatch",
        "core_auditevent",
    }

    print("\n=== REQUIRED TABLES ===")
    for table in sorted(required_tables):
        print(f"{table}: {'PRESENT' if table in tables else 'MISSING'}")

    loader = MigrationLoader(connection, ignore_no_migrations=True)
    applied = loader.applied_migrations
    pending = sorted(loader.graph.leaf_nodes())

    print("\n=== CORE MIGRATION STATUS ===")
    for key in sorted(k for k in loader.graph.nodes if k[0] == "core"):
        print(f"{key[0]}.{key[1]}: {'APPLIED' if key in applied else 'NOT APPLIED'}")

    print("\n=== ACCOUNTS MIGRATION STATUS ===")
    account_nodes = sorted(k for k in loader.graph.nodes if k[0] == "accounts")
    if account_nodes:
        for key in account_nodes:
            print(f"{key[0]}.{key[1]}: {'APPLIED' if key in applied else 'NOT APPLIED'}")
    else:
        print("No accounts migrations defined.")

    print("\n=== UNAPPLIED MIGRATIONS ===")
    unapplied = sorted(loader.graph.leaf_nodes())
    found = False
    for app_label, migration_name in unapplied:
        key = (app_label, migration_name)
        if key not in applied:
            print(f"{app_label}.{migration_name}")
            found = True

    if not found:
        print("No unapplied leaf migrations detected.")

    print("\n=== CHECK COMPLETE — NO MIGRATIONS RUN ===")

except Exception as exc:
    print("\nCHECK FAILED:", type(exc).__name__, str(exc))
    raise
