"""Быстрая проверка перед запуском сервера."""
from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from spamimpakter.pyrogram_compat import assert_pyrogram_usable  # noqa: E402
from spamimpakter.session_utils import validate_session_file  # noqa: E402


def _fail(msg: str) -> int:
    print(f"[smoke] FAIL: {msg}")
    return 1


def _check_postgres() -> int | None:
    env_file = ROOT / ".runtime.env"
    if not env_file.exists():
        return None
    text = env_file.read_text(encoding="utf-8")
    if "SPAMIMPAKTER_USE_PG=1" not in text:
        return None
    try:
        from spamimpakter.pg_runtime import ensure_pg_dsn, test_dsn

        dsn = ensure_pg_dsn(autostart=False)
        if not dsn or not test_dsn(dsn):
            return _fail(
                "PostgreSQL not reachable. Run stop.bat then start.bat "
                "(bootstrap must start embedded PG first)."
            )
        print(f"[smoke] PG OK — {dsn.rsplit('@', 1)[-1]}")
        from spamimpakter.db import Store

        s = Store(ROOT / "data" / "spamimpakter.db")
        if not s._pg_fastpath:
            return _fail("Store fell back to SQLite — PG expected")
        print("[smoke] Store on PostgreSQL")
    except Exception as e:
        return _fail(f"PostgreSQL check: {e}")
    return None


def main() -> int:
    print("[smoke] SPAMIMPAKTER preflight")
    try:
        assert_pyrogram_usable()
    except RuntimeError as e:
        return _fail(str(e))

    pg_err = _check_postgres()
    if pg_err is not None:
        return pg_err

    db_path = ROOT / "data" / "spamimpakter.db"
    if not db_path.exists():
        return _fail(f"database missing: {db_path}")

    from spamimpakter.db import Store

    try:
        store = Store(db_path)
        with store._conn_ro() as conn:
            acc_cnt = int(conn.execute("SELECT COUNT(*) FROM accounts").fetchone()[0] or 0)
            running_jobs = int(
                conn.execute(
                    "SELECT COUNT(*) FROM broadcast_jobs WHERE status IN ('running','waiting')"
                ).fetchone()[0]
                or 0
            )
    except Exception as e:
        return _fail(f"database error: {e}")

    api_ok = False
    cfg = ROOT / "config" / "accounts.json"
    if cfg.exists():
        try:
            data = json.loads(cfg.read_text(encoding="utf-8"))
            api_ok = bool(data.get("api_id") and data.get("api_hash"))
        except Exception:
            pass
    if not api_ok and db_path.exists():
        try:
            with Store(db_path)._conn_ro() as conn:
                row = conn.execute("SELECT value FROM settings WHERE key='api_id'").fetchone()
                row2 = conn.execute("SELECT value FROM settings WHERE key='api_hash'").fetchone()
            api_ok = bool(row and row[0] and row2 and row2[0])
        except Exception:
            pass
    if not api_ok:
        return _fail("Telegram api_id/api_hash not configured")

    sessions_dir = ROOT / "sessions"
    bad_sessions: list[str] = []
    if sessions_dir.is_dir():
        for p in sessions_dir.glob("*.session"):
            if p.name.endswith("-journal"):
                continue
            if not validate_session_file(p):
                bad_sessions.append(p.name)
    if bad_sessions:
        print(f"[smoke] WARN: invalid session files ({len(bad_sessions)}): {', '.join(bad_sessions[:5])}")

    if running_jobs:
        print(f"[smoke] WARN: {running_jobs} broadcast job(s) still running/waiting in DB")

    print(f"[smoke] OK — accounts={acc_cnt}, db={db_path.name}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
