"""Minimal check for per-account pair routing + auto-pair dedupe.

Run: python3 test_routing.py   (no DB / network needed)
"""
import sys
from types import SimpleNamespace

import forwarding  # imports core only for TYPE_CHECKING


class FakeCore:
    def __init__(self, pairs):
        self._pairs = pairs
        self._forwarding = True
        self._signal_processor = None
        self._llm_engine = None
        self._ctrader_client = None
        self._run_db = lambda *a, **k: None


class FakeEvent:
    def __init__(self, chat_id, msg_id=None, deleted_ids=None, client=None):
        self.chat_id = chat_id
        self.id = msg_id
        self._client = client
        self.message = SimpleNamespace(id=msg_id, message="x")
        self.deleted_ids = deleted_ids


def make_client(account_id):
    return SimpleNamespace(
        _id=account_id,
        add_event_handler=lambda *a, **k: None,
        remove_event_handler=lambda *a, **k: None,
    )


def build():
    # Account 1 owns source 111; account 2 owns source 222; source 333 is auto.
    core = FakeCore({
        1: {111: [{"id": 1, "dest_chat_id": 900}]},
        2: {222: [{"id": 2, "dest_chat_id": 901}]},
        None: {333: [{"id": 3, "dest_chat_id": 902}]},
    })
    fwd = forwarding.MessageForwarder(core)
    c1, c2 = make_client(1), make_client(2)
    fwd.install(c1, 1)
    fwd.install(c2, 2)
    return fwd, c1, c2


def main():
    fwd, c1, c2 = build()

    # Bound pairs: only the owning account's client sees them.
    e = FakeEvent(111, msg_id=100, client=c1)
    assert len(fwd._lookup_pairs(e, 111)) == 1, "account 1 must see its bound pair"
    e2 = FakeEvent(111, msg_id=101, client=c2)
    assert fwd._lookup_pairs(e2, 111) == [], "account 2 must NOT see account 1's pair"

    # Auto pair: first client claims, second is deduped.
    ea = FakeEvent(333, msg_id=200, client=c1)
    pa = fwd._lookup_pairs(ea, 333)
    assert len(pa) == 1, "first client claims the auto pair"
    eb = FakeEvent(333, msg_id=200, client=c2)
    assert fwd._lookup_pairs(eb, 333) == [], "second client deduped for same message"
    ec = FakeEvent(333, msg_id=201, client=c1)
    assert len(fwd._lookup_pairs(ec, 333)) == 1, "different message is not deduped"

    # Delete events: claim per deleted id, not per event.
    ed1 = FakeEvent(333, deleted_ids=[1, 2], client=c1)
    assert fwd._lookup_pairs(ed1, 333, claim=False) == [], "delete path returns bound pairs only (auto handled in loop)"
    assert fwd._claim_auto((333, 1)) is True
    assert fwd._claim_auto((333, 1)) is False, "same deleted id not claimed twice"
    assert fwd._claim_auto((333, 2)) is True, "different deleted id is claimable"

    print("OK: routing + dedupe behave as expected")


if __name__ == "__main__":
    main()
