"""Проверка таблиц БД и состояния очереди SMS."""
from __future__ import annotations

import asyncio
import sys
from pathlib import Path

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

from sqlalchemy import text
from app.database.engine import async_session, init_db
from app.database import models  # noqa: F401
from app.database.models import Base


EXPECTED = set(Base.metadata.tables.keys())


async def main() -> None:
    await init_db()
    async with async_session() as s:
        tables = {
            r[0]
            for r in (
                await s.execute(
                    text("SELECT name FROM sqlite_master WHERE type='table'")
                )
            ).fetchall()
        }
        print("tables_ok:", EXPECTED.issubset(tables))
        print("expected:", sorted(EXPECTED))
        print("missing:", sorted(EXPECTED - tables))
        print("extra:", sorted(tables - EXPECTED - {"sqlite_sequence"}))

        for t in sorted(EXPECTED):
            try:
                n = (
                    await s.execute(text(f"SELECT COUNT(*) FROM [{t}]"))
                ).scalar()
                print(f"count[{t}]={n}")
            except Exception as e:
                print(f"count[{t}]=ERROR {e}")

        idxs = (
            await s.execute(
                text(
                    "SELECT name FROM sqlite_master "
                    "WHERE type='index' AND tbl_name='pending_sms'"
                )
            )
        ).fetchall()
        print("pending_sms_indexes:", [x[0] for x in idxs])

        pending = (
            await s.execute(
                text(
                    "SELECT COUNT(*) FROM pending_sms WHERE status='pending'"
                )
            )
        ).scalar()
        dups = (
            await s.execute(
                text(
                    "SELECT COUNT(*) FROM ("
                    " SELECT phone_number FROM pending_sms "
                    " WHERE status='pending' "
                    " GROUP BY phone_number HAVING COUNT(*) > 1"
                    ")"
                )
            )
        ).scalar()
        print(f"pending={pending} dup_groups={dups}")

    from config import (
        SMS_PAUSE_AFTER_SEND_SEC_MIN,
        SMS_PAUSE_AFTER_SEND_SEC_MAX,
        PENDING_SMS_TICK_SEC,
        SMS_DAILY_LIMIT,
    )
    from app.database.crud_static import count_today_sent_sms
    from app.database.crud_filter import get_filter_settings_dict
    from app.schedule_utils import is_within_window, now_in_bot_tz

    today = await count_today_sent_sms()
    print(
        f"pause={SMS_PAUSE_AFTER_SEND_SEC_MIN}-{SMS_PAUSE_AFTER_SEND_SEC_MAX}s "
        f"tick={PENDING_SMS_TICK_SEC}s daily_limit={SMS_DAILY_LIMIT} today_sent={today}"
    )
    print("now_bot_tz:", now_in_bot_tz().isoformat())

    # расписание первого пользователя с pending
    async with async_session() as s:
        uid = (
            await s.execute(
                text(
                    "SELECT user_id FROM pending_sms "
                    "WHERE status='pending' LIMIT 1"
                )
            )
        ).scalar()
    if uid:
        settings = await get_filter_settings_dict(int(uid)) or {}
        wf, wt, wd = (
            settings.get("work_from"),
            settings.get("work_to"),
            settings.get("work_days"),
        )
        print(
            f"user={uid} work={wf}-{wt} days={wd} "
            f"in_window={is_within_window(wf, wt, wd)}"
        )


if __name__ == "__main__":
    asyncio.run(main())
