#!/usr/bin/env python3
"""Read-only diagnostic for SKEVER Portal V1 (Django on cPanel/Passenger).
Run from cPanel Setup Python App -> Execute Python Script using the app's Python environment.
Does NOT migrate, write to, repair, or modify the database.
"""
from __future__ import print_function
import os, sys, traceback, importlib
from pathlib import Path
APP_ROOT = Path(__file__).resolve().parent
os.chdir(str(APP_ROOT))
if str(APP_ROOT) not in sys.path: sys.path.insert(0, str(APP_ROOT))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.config.settings")
issues, warnings = [], []
def report(label, ok, detail=""):
    print("[{}] {}{}".format("OK" if ok else "FAIL", label, (": " + str(detail)) if detail else ""))
    if not ok: issues.append(label + (": " + str(detail) if detail else ""))
def warn(label, detail=""):
    print("[WARN] {}{}".format(label, (": " + str(detail)) if detail else "")); warnings.append(label)
print("=" * 72); print("SKEVER PORTAL V1 — READ-ONLY DIAGNOSTIC"); print("=" * 72)
print("Application root:", APP_ROOT); print("Python:", sys.version.replace("\n", " ")); print("Working directory:", os.getcwd()); print("Settings module:", os.environ.get("DJANGO_SETTINGS_MODULE")); print()
for rel in ["manage.py", "passenger_wsgi.py", "config/__init__.py", "config/config/__init__.py", "config/config/settings.py", "config/urls.py", "core/__init__.py", "core/views.py", "core/workflow_views.py", "core/orders_views.py", "db.sqlite3"]:
    p = APP_ROOT / rel
    report("File exists: " + rel, p.is_file(), "not found at " + str(p) if not p.is_file() else "size={} bytes".format(p.stat().st_size))
print()
try:
    import django
    print("Django version:", django.get_version()); django.setup(); report("Django setup", True)
except Exception as exc:
    report("Django setup", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
    print("\nDIAGNOSTIC STOPPED: Django could not initialize."); print("Summary: {} failure(s), {} warning(s).".format(len(issues), len(warnings))); sys.exit(1)
try:
    from django.conf import settings
    report("DEBUG setting available", hasattr(settings, "DEBUG"), "DEBUG={}".format(getattr(settings, "DEBUG", "<missing>")))
    report("ROOT_URLCONF configured", bool(getattr(settings, "ROOT_URLCONF", None)), getattr(settings, "ROOT_URLCONF", "<missing>"))
    report("Database default configured", bool(getattr(settings, "DATABASES", {}).get("default", {}).get("ENGINE")), getattr(settings, "DATABASES", {}).get("default", {}).get("ENGINE", "<missing>"))
    report("Allowed hosts configured", bool(getattr(settings, "ALLOWED_HOSTS", [])), "count={}".format(len(getattr(settings, "ALLOWED_HOSTS", []))))
except Exception as exc:
    report("Settings sanity", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
print()
try:
    importlib.import_module("config.urls"); report("URL configuration imports", True, "config.urls")
except Exception as exc:
    report("URL configuration imports", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
try:
    mod = importlib.import_module("core.workflow_views"); required = ["order_accept", "order_hold", "order_decline", "order_start_processing"]
    missing = [n for n in required if not callable(getattr(mod, n, None))]
    report("Workflow view functions", not missing, "missing: " + ", ".join(missing) if missing else ", ".join(required))
except Exception as exc:
    report("Workflow module imports", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
try:
    mod = importlib.import_module("core.orders_views"); required = ["orders_list", "order_detail"]
    missing = [n for n in required if not callable(getattr(mod, n, None))]
    report("Orders workspace view functions", not missing, "missing: " + ", ".join(missing) if missing else ", ".join(required))
except Exception as exc:
    report("Orders workspace module imports", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
print()
try:
    from django.urls import reverse, resolve
    routes = [("dashboard", "dashboard", None), ("orders_list", "orders_list", None), ("order_detail", "order_detail", {"order_id": 1}), ("order_accept", "order_accept", {"order_id": 1}), ("order_hold", "order_hold", {"order_id": 1}), ("order_decline", "order_decline", {"order_id": 1}), ("order_start_processing", "order_start_processing", {"order_id": 1})]
    for label, name, kwargs in routes:
        try:
            url = reverse(name, kwargs=kwargs); match = resolve(url); report("Route " + label, True, "{} -> {}".format(url, match.view_name))
        except Exception as exc: report("Route " + label, False, "{}: {}".format(type(exc).__name__, exc))
except Exception as exc:
    report("URL resolver", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
print()
try:
    from django.db import connection
    connection.ensure_connection(); report("Database connection", True, connection.settings_dict.get("ENGINE", "engine unknown"))
    with connection.cursor() as cursor:
        cursor.execute("SELECT 1"); report("Database SELECT 1", cursor.fetchone()[0] == 1)
        if connection.vendor == "sqlite":
            cursor.execute("PRAGMA quick_check"); row = cursor.fetchone(); result = row[0] if row else "no result"
            report("SQLite quick_check", result == "ok", result)
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table'"); tables = {r[0] for r in cursor.fetchall()}
            for table in ["core_order", "core_orderitem", "core_customer", "core_payment", "core_dispatch", "core_auditevent"]:
                report("Database table " + table, table in tables, "present" if table in tables else "missing")
except Exception as exc:
    report("Database checks", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
print()
try:
    from django.template.loader import get_template
    for name in ["dashboard.html", "registration/login.html"]:
        try: get_template(name); report("Template loads: " + name, True)
        except Exception as exc: warn("Template not found/loadable: " + name, "{}: {}".format(type(exc).__name__, exc))
except Exception as exc: warn("Template loader check unavailable", "{}: {}".format(type(exc).__name__, exc))
print()
try:
    from django.db import connections
    from django.db.migrations.executor import MigrationExecutor
    executor = MigrationExecutor(connections["default"]); plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
    report("Migration state inspection", True, "unapplied migration count={}".format(len(plan)))
    if plan:
        for migration, backwards in plan[:20]: print("  UNAPPLIED:", migration.app_label, migration.name)
        warn("Unapplied migrations detected", "This script did not run them; inspect before deciding what to do.")
except Exception as exc:
    report("Migration state inspection", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
print()
try:
    importlib.import_module("passenger_wsgi"); report("Passenger WSGI module imports", True)
except Exception as exc:
    report("Passenger WSGI module imports", False, "{}: {}".format(type(exc).__name__, exc)); traceback.print_exc()
print(); print("=" * 72); print("DIAGNOSTIC SUMMARY"); print("Failures:", len(issues)); print("Warnings:", len(warnings))
if issues:
    print("\nFAILURES:")
    for item in issues: print(" -", item)
if warnings:
    print("\nWARNINGS:")
    for item in warnings: print(" -", item)
print("\nRead-only diagnostic complete. No migrations or database writes were performed.")
print("If browser still fails, check cPanel Errors / Passenger logs for the same request timestamp."); print("=" * 72)
