"""Telegram ITSELF failing (timeouts, internal errors) while the sync reads a channel: the read is repeated, a post Telegram
won't hand over is left exactly as saved (never taken for deleted), and when everything fails the look is given up quietly."""
import asyncio
import datetime
import logging
from types import SimpleNamespace

import pytest
from telethon import errors, types

from app import replace_engine, sync_engine, syncer
from app.replace_engine import TelegramStuck, fetch_messages, is_stuck
from app.sync_engine import MAX_FAILS, Fails, SyncOptions, SyncReport, _compare_saved, read_ids, sync_channel, sync_ids
from app.syncer import Syncer

UNSUCCESSFUL = "Request was unsuccessful 6 time(s)"  # what Telethon raises when all its tries failed


def run(coro):
    return asyncio.run(coro)


class Flaky:
    """get_messages like Telethon's after it gave up on a request: it raises when `bad(ids)` says so."""

    def __init__(self, bad=lambda ids: False, exc=lambda: ValueError(UNSUCCESSFUL), msgs=None):
        self.bad, self.exc, self.msgs, self.calls = bad, exc, msgs or {}, []

    async def get_messages(self, peer, ids=None):
        self.calls.append(list(ids))
        if self.bad(list(ids)):
            raise self.exc()
        return [self.msgs.get(i) for i in ids]


class Db:
    def __init__(self, ids):
        self.posts = [SimpleNamespace(message_id=i, updated_at=None, sent_at=None, text="") for i in ids]
        self.forgotten = []

    async def sent_posts(self, cid):
        return list(self.posts)

    async def posts_at(self, cid, ids):
        return [p for p in self.posts if p.message_id in set(ids)]

    async def forget_posts(self, cid, ids):
        self.forgotten.extend(ids)
        return len(ids)

    async def get_sync(self, cid):
        return None


CH = SimpleNamespace(id=-1001, title="Channel")


@pytest.fixture(autouse=True)
def quick(monkeypatch):
    monkeypatch.setattr(replace_engine, "STUCK_WAITS", (0, 0))  # no real pauses
    monkeypatch.setattr(sync_engine, "peer_of", lambda ch: "peer")

    async def probe(client, peer):
        return 100, None, None

    monkeypatch.setattr(sync_engine, "probe_channel", probe)


# ----------------------------------------------------------------------------------------------- fetch_messages
def test_a_read_that_fails_is_repeated_and_works_later():
    n = {"left": 2}

    def bad(ids):
        n["left"] -= 1
        return n["left"] >= 0

    client = Flaky(bad=bad, msgs={5: "five"})
    assert run(fetch_messages(client, "peer", [5, 6])) == ["five", None]
    assert len(client.calls) == 3  # two failures, then the answer


def test_a_read_that_never_works_ends_as_telegram_stuck():
    client = Flaky(bad=lambda ids: True)
    with pytest.raises(TelegramStuck) as info:
        run(fetch_messages(client, "peer", list(range(100, 200))))
    assert isinstance(info.value, ValueError)  # handlers that caught Telethon's own ValueError still catch it
    assert "100-199" in str(info.value) and UNSUCCESSFUL in str(info.value)
    assert len(client.calls) == 3  # the first try + one per pause


def test_a_refusal_is_not_repeated():
    client = Flaky(bad=lambda ids: True, exc=lambda: errors.ChannelPrivateError(request=None))
    with pytest.raises(errors.ChannelPrivateError):
        run(fetch_messages(client, "peer", [1]))
    assert len(client.calls) == 1


def test_waits_can_be_switched_off():
    client = Flaky(bad=lambda ids: True)
    with pytest.raises(TelegramStuck):
        run(fetch_messages(client, "peer", [1, 2], waits=()))
    assert len(client.calls) == 1


@pytest.mark.parametrize(
    "exc, stuck",
    [
        (ValueError(UNSUCCESSFUL), True),
        (errors.RpcMcgetFailError(request=None), True),
        (errors.ServerError(request=None, message="INTERNAL"), True),
        (errors.TimedOutError(None, "Timeout"), True),
        (TelegramStuck("x"), True),
        (ValueError("something else"), False),
        (errors.ChannelPrivateError(request=None), False),
        (errors.FloodWaitError(request=None, capture=5), False),
        (RuntimeError(UNSUCCESSFUL), False),
    ],
)
def test_what_counts_as_telegram_failing(exc, stuck):
    assert is_stuck(exc) is stuck


# ----------------------------------------------------------------------------------------------- read_ids
def test_one_post_that_breaks_the_request_is_found_and_the_rest_is_read():
    client = Flaky(bad=lambda ids: 57 in ids)
    fails, lost = Fails(), []
    got = run(read_ids(client, "peer", list(range(1, 101)), fails, lost, pause=0))
    assert sorted(got) == [i for i in range(1, 101) if i != 57]
    assert lost == [57]  # noted, to be left as saved
    assert fails.n == 3  # the batch, the piece of ten, the post alone


def test_two_bad_posts_in_different_places():
    client = Flaky(bad=lambda ids: 5 in ids or 77 in ids)
    lost = []
    got = run(read_ids(client, "peer", list(range(1, 101)), Fails(), lost, pause=0))
    assert sorted(got) == [i for i in range(1, 101) if i not in (5, 77)]
    assert sorted(lost) == [5, 77]


def test_a_batch_that_is_only_too_heavy_is_read_in_pieces():
    client = Flaky(bad=lambda ids: len(ids) > 30)  # times out whenever many posts are asked for at once
    lost = []
    got = run(read_ids(client, "peer", list(range(1, 101)), Fails(), lost, pause=0))
    assert sorted(got) == list(range(1, 101))
    assert not lost  # every post was read after all


def test_when_telegram_fails_for_everything_the_look_is_given_up():
    client = Flaky(bad=lambda ids: True)
    fails = Fails()
    with pytest.raises(TelegramStuck):
        run(read_ids(client, "peer", list(range(1, 101)), fails, [], pause=0))
    assert fails.n == MAX_FAILS + 1
    assert len(client.calls) == 3 + MAX_FAILS  # the batch is tried 3 times, then each failing piece once: it ends soon


# ----------------------------------------------------------------------------------------------- the comparison
def compare(db, client, **kw):
    rep = SyncReport(channel=CH)
    run(_compare_saved(client, db, CH, rep, SyncOptions(pause=0), lambda: False, None, **kw))
    return rep


def test_a_post_telegram_wont_hand_over_is_kept_while_the_deleted_ones_leave():
    db = Db([1, 2, 3, 4])
    rep = compare(db, Flaky(bad=lambda ids: 2 in ids))  # 1, 3, 4 are gone from the channel; 2 can't be read
    assert db.forgotten == [1, 3, 4]
    assert rep.deleted == [1, 3, 4]
    assert 2 in rep.restricted and not rep.error and not rep.anomaly


def test_unreadable_posts_do_not_switch_off_the_everything_was_deleted_check():
    db = Db(range(1, 8))  # seven saved posts: six look deleted, the seventh can't be read - the bot may be blind
    rep = compare(db, Flaky(bad=lambda ids: 7 in ids))
    assert db.forgotten == []
    assert rep.anomaly and "All 6 saved posts look deleted" in rep.anomaly


def service(i):
    return types.MessageService(id=i, peer_id=types.PeerChannel(1), date=datetime.datetime.now(datetime.timezone.utc), action=types.MessageActionEmpty())


def test_one_bad_post_alone_in_the_last_batch_does_not_block_the_channel():
    db = Db(range(1, 102))  # a hundred posts and one more
    client = Flaky(bad=lambda ids: 101 in ids, msgs={i: service(i) for i in range(1, 101)})
    rep = compare(db, client)
    assert 101 in rep.restricted and not rep.error and not rep.anomaly
    assert db.forgotten == []


def test_a_small_channel_where_nothing_can_be_read_is_an_outage_not_many_bad_posts():
    db = Db([1, 2, 3])
    with pytest.raises(TelegramStuck):
        compare(db, Flaky(bad=lambda ids: True))
    assert db.forgotten == []


def test_an_outage_decides_nothing():
    db = Db(range(1, 8))
    with pytest.raises(TelegramStuck):
        compare(db, Flaky(bad=lambda ids: True))
    assert db.forgotten == []


# ----------------------------------------------------------------------------------------------- the entry points
def test_sync_channel_reports_an_outage_instead_of_raising():
    db = Db([1, 2, 3])
    rep = run(sync_channel(Flaky(bad=lambda ids: True), db, CH, SyncOptions(pause=0)))
    assert rep.stuck and "cut short" in rep.error and UNSUCCESSFUL in rep.error
    assert db.forgotten == []


def test_sync_channel_still_reports_refusals_the_old_way():
    db = Db([1, 2, 3])
    client = Flaky(bad=lambda ids: True, exc=lambda: errors.ChannelPrivateError(request=None))
    rep = run(sync_channel(client, db, CH, SyncOptions(pause=0)))
    assert not rep.stuck and rep.error.startswith("Telegram refused")


def test_sync_ids_reports_an_outage_instead_of_raising():
    db = Db([5, 6])
    rep = run(sync_ids(Flaky(bad=lambda ids: True), db, CH, [5, 6], SyncOptions(pause=0)))
    assert rep.stuck and "cut short" in rep.error
    assert db.forgotten == []


# ----------------------------------------------------------------------------------------------- the Syncer
class Sender:
    def __init__(self):
        self.sent = []

    async def send_message(self, uid, text, link_preview=False):
        self.sent.append((uid, text))


def make_syncer():
    sender = Sender()
    cfg = SimpleNamespace(
        owners={7}, sync_interval_minutes=60, delete_service_messages=False, import_old_posts=False
    )
    ctx = SimpleNamespace(cfg=cfg, client=sender, db=None, lock=asyncio.Lock(), sync_ignore=set())
    return Syncer(ctx), sender


def stuck_report():
    return SyncReport(channel=CH, error="Telegram kept failing - cut short", stuck=True)


def test_the_owners_are_told_when_telegram_keeps_failing_look_after_look():
    async def go():
        s, sender = make_syncer()
        for _ in range(2):
            await s._after(CH, stuck_report())
        assert sender.sent == []  # one or two bad looks are a blip
        await s._after(CH, stuck_report())
        assert len(sender.sent) == 1 and sender.sent[0][0] == 7 and "Channel" in sender.sent[0][1]
        await s._after(CH, stuck_report())
        assert len(sender.sent) == 1  # once a day

    run(go())


def test_a_good_look_starts_the_count_again():
    async def go():
        s, sender = make_syncer()
        await s._after(CH, stuck_report())
        await s._after(CH, stuck_report())
        await s._after(CH, SyncReport(channel=CH))  # Telegram answers again
        await s._after(CH, stuck_report())
        await s._after(CH, stuck_report())
        assert sender.sent == []

    run(go())


def test_run_all_logs_telegram_trouble_quietly_and_real_bugs_loudly(monkeypatch, caplog):
    async def go(exc):
        s, _ = make_syncer()

        async def boom(*a, **k):
            raise exc

        monkeypatch.setattr(syncer, "sync_channel", boom)
        return (await s.run_all([CH]))[0]

    with caplog.at_level(logging.INFO):
        rep = run(go(ValueError(UNSUCCESSFUL)))
    assert rep.stuck and "cut short" in rep.error
    assert not [r for r in caplog.records if r.levelno >= logging.ERROR]  # no traceback in the log

    caplog.clear()
    with caplog.at_level(logging.INFO):
        rep = run(go(ValueError("boom")))
    assert not rep.stuck and rep.error == "ValueError: boom"
    assert [r for r in caplog.records if r.levelno >= logging.ERROR]


def test_live_changes_log_telegram_trouble_quietly_too(monkeypatch, caplog):
    async def go(exc):
        s, _ = make_syncer()

        async def channel(cid):
            return CH

        async def boom(*a, **k):
            raise exc

        monkeypatch.setattr(s, "channel", channel)
        monkeypatch.setattr(syncer, "sync_ids", boom)
        await s._process({CH.id: {5}}, {})
        return s.last_reports[CH.id]

    with caplog.at_level(logging.INFO):
        rep = run(go(errors.RpcCallFailError(request=None)))
    assert rep.stuck and "cut short" in rep.error
    assert not [r for r in caplog.records if r.levelno >= logging.ERROR]

    caplog.clear()
    with caplog.at_level(logging.INFO):
        rep = run(go(ValueError("boom")))
    assert not rep.stuck and rep.error == "ValueError: boom"
    assert [r for r in caplog.records if r.levelno >= logging.ERROR]
