#!/usr/bin/env python3
"""Offline setup checks. Does not contact Telegram or print the bot token."""
from pathlib import Path
import sqlite3
import sys
import config
import spg_support_bot as bot

root = Path(__file__).resolve().parent
print("SPG Support Suite Pro — offline self-check")
print("-----------------------------------------")
if not config.BOT_TOKEN or config.BOT_TOKEN == "PASTE_SUPPORT_BOT_TOKEN_HERE":
    print("[WARN] Set BOT_TOKEN in config.py before live testing.")
else:
    print("[OK] Bot token field is populated (value hidden).")
if not any(isinstance(x, int) and x > 0 for x in config.OWNER_IDS):
    print("[WARN] Set at least one numeric system-admin ID in config.py.")
else:
    print("[OK] At least one system-admin ID is configured.")
if config.TIMEZONE != "Asia/Kolkata":
    print(f"[WARN] Timezone is {config.TIMEZONE}, expected Asia/Kolkata for India.")
else:
    print("[OK] India timezone is configured.")
image = Path(config.WELCOME_IMAGE_PATH)
if not image.is_absolute():
    image = root / image
if not image.exists():
    print("[WARN] Welcome image file is missing.")
else:
    print(f"[OK] Welcome image found ({image.stat().st_size:,} bytes).")
print("[OK] Welcome message length:", len(config.WELCOME_TEXT), "characters")
print("[OK] Channel membership is optional by design.")
for sample, expected, expected_urgent in [
    ("my withdrawal is pending", "withdrawal", False),
    ("payment deposit missing", "finance", False),
    ("my account is hacked scam", "other", True),
    ("मेरा खाता हैक हो गया", "other", True),
]:
    got, urgent = bot.classify_message(sample)
    ok = (got == expected and urgent == expected_urgent)
    print(f"[{'OK' if ok else 'FAIL'}] Routing sample -> category={got}, priority_alert={urgent}")
    if not ok:
        sys.exit(1)
# Verify there is no customer-facing emergency button.
keyboard_text = str(bot.home_keyboard().inline_keyboard) + str(bot.category_keyboard().inline_keyboard)
if "Emergency Support" in keyboard_text or "category:emergency" in keyboard_text:
    print("[FAIL] Emergency button was found in the menu.")
    sys.exit(1)
print("[OK] No emergency button; keyword priority detection is enabled.")
# Initialize the app database and verify the additive tables and shift schema.
try:
    bot.db_init()
    with bot.db_connect() as conn:
        tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
        manager_sql = conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='managers'").fetchone()[0]
    required = {"tickets", "messages", "delivery_outbox", "staff_delivery_outbox", "staff_lead_map", "webhook_inbox", "managers", "audit_logs"}
    missing = required - tables
    if missing:
        print("[FAIL] Missing database tables:", ", ".join(sorted(missing)))
        sys.exit(1)
    if "BETWEEN 1 AND 24" not in manager_sql:
        print("[FAIL] Shift schema does not allow durations from 1 to 24 hours.")
        sys.exit(1)
    print("[OK] SQLite schema, durable queues, and configurable 1–24h shifts verified.")
except Exception as exc:
    print("[FAIL] Database schema check failed:", type(exc).__name__, str(exc))
    raise
print("\nSelf-check complete. This does not verify live token, webhooks, manager DMs, hosting limits, or Telegram delivery.")
