"""Прогоняет сценарии через настоящий Dispatcher с подменённым Bot (без сети)."""
import asyncio
import os
import sys
import tempfile
from datetime import datetime

tmp = tempfile.mkdtemp()
os.environ.update(BOT_TOKEN="123:ABC", OWNER_ID="42", DB_PATH=f"{tmp}/t.db")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from aiogram import Bot, Dispatcher  # noqa: E402
from aiogram.client.default import DefaultBotProperties  # noqa: E402
from aiogram.fsm.storage.memory import MemoryStorage  # noqa: E402
from aiogram.methods import AnswerCallbackQuery, EditMessageText, SendMessage  # noqa: E402
from aiogram.types import CallbackQuery, Chat, Message, Update, User  # noqa: E402

import bot as B  # noqa: E402

OUT = []
uid = 0


class FakeBot(Bot):
    async def __call__(self, method, request_timeout=None):
        if isinstance(method, (SendMessage, EditMessageText)):
            kb = method.reply_markup
            btns = []
            if kb is not None and hasattr(kb, "inline_keyboard"):
                btns = [(b.text, b.callback_data) for row in kb.inline_keyboard for b in row]
            OUT.append((method.text, btns))
            return Message(message_id=1, date=datetime.now(), chat=Chat(id=42, type="private"), text=method.text)
        if isinstance(method, AnswerCallbackQuery):
            return True
        return True


def upd(user_id=42, text=None, data=None):
    global uid
    uid += 1
    u = User(id=user_id, is_bot=False, first_name="D")
    msg = Message(message_id=uid, date=datetime.now(), chat=Chat(id=user_id, type="private"), from_user=u,
                  text=text or "x")
    if data:
        return Update(update_id=uid, callback_query=CallbackQuery(id=str(uid), from_user=u, chat_instance="c",
                                                                  data=data, message=msg))
    return Update(update_id=uid, message=msg)


async def main():
    bot = FakeBot("123:ABC", default=DefaultBotProperties(parse_mode="HTML"))
    dp = B.build_dispatcher()  # с SQLite FSM-хранилищем, как в проде

    async def say(text=None, data=None, user=42):
        OUT.clear()
        await dp.feed_update(bot, upd(user, text, data))
        return OUT[-1] if OUT else (None, [])

    # чужой пользователь — тишина
    assert (await say("/start", user=777))[0] is None

    # кредит
    await say("➕ Добавить")
    await say(data="k:credit")
    await say("Ипотека")
    await say(data="c:UZS")
    await say("12 млн")
    await say("3 000 000")
    await say(data="p:month")
    t, b = await say("15")
    assert "Проверь" in t and "за 3 дн." in t, t
    t, b = await say(data="save")
    print(t, "\n", b, "\n")
    oid = int([d for _, d in b if d.startswith("q:")][0][2:])

    # меню перебивает мастер
    await say("➕ Добавить"); await say(data="k:sub")
    t, _ = await say("📊 Сводка")
    assert "Сводка" in t

    # подписка в USD
    await say("➕ Добавить"); await say(data="k:sub"); await say("Netflix"); await say(data="c:USD")
    await say("9.99"); await say(data="p:month"); await say("02.12"); await say(data="save")

    # мне должны, разом, без срока
    await say("➕ Добавить"); await say(data="k:owed_me"); await say("Алишер"); await say(data="c:UZS")
    await say("2 000 000"); await say(data="skip"); t, _ = await say(data="skip")
    assert "Без срока" in t, t
    await say(data="save")

    # быстрый платёж + отмена
    t, b = await say(data=f"q:{oid}")
    print(t, "\n")
    assert "9 000 000" in t
    undo = [d for _, d in b if d.startswith("undo:")][0]
    t, _ = await say(data=undo)
    assert "12 000 000" in t and "отменён" in t

    # частично заранее, потом добиваем остаток периода кнопкой
    await say(data=f"pay:{oid}")
    t, _ = await say("1 млн")
    print(t, "\n")
    assert "осталось <b>2 000 000" in t, t
    t, b = await say(data=f"ob:{oid}")
    print(t, "\n", b, "\n")
    assert ("✅ Оплачено 2 000 000 сум", f"q:{oid}") in b
    t, _ = await say(data=f"q:{oid}")
    print(t, "\n")
    assert "досрочно" in t and "15.01.2027" in t, t
    # частично ещё раз, чтобы проверить сводку
    await say(data=f"pay:{oid}"); await say("500к")

    # Алишер вернул всё
    aid = [o["id"] for o in B.db.list() if o["name"] == "Алишер"][0]
    await say(data=f"pay:{aid}")
    t, _ = await say("2000000")
    assert "Полностью закрыто" in t, t

    # досрочное погашение кредита целиком + отмена
    t, b = await say(data=f"all:{oid}")
    assert "Полностью закрыто" in t, t
    undo = [d for _, d in b if d.startswith("undo:")][0]
    t, _ = await say(data=undo)
    assert "отменён" in t and "Внесено заранее: 500 000" in t, t

    t, b = await say("📋 Список"); print(t, "\n", b, "\n")
    t, _ = await say("📊 Сводка"); print(t, "\n")

    # напоминания: Netflix 02.12 (через 3 дня от 29.11/30.11) -> зависит от даты, проверим на фикс. дате
    OUT.clear()
    from datetime import date
    n = await B.send_reminders(bot, date(2026, 12, 12))      # Ипотека 15.01? нет; Netflix 02.12 просрочен
    print("reminders@12.12:", n, *[o[0] for o in OUT], sep="\n")
    OUT.clear()
    n = await B.send_reminders(bot, date(2026, 11, 29))      # Netflix 02.12 — ровно за 3 дня
    assert n == 1 and "Netflix" in OUT[0][0], OUT
    print("\nALL OK")


asyncio.run(main())
