"""Show unread chats — your real inbox view.

Usage:
    python tg_inbox.py                          # all unread, sorted by count desc
    python tg_inbox.py --top 20
    python tg_inbox.py --include-archived
    python tg_inbox.py --mark-read "Born2bero"  # zero-out a specific chat
    python tg_inbox.py --mark-all-read --yes    # nuke ALL unread (destructive)
"""
from __future__ import annotations

import argparse
import asyncio

from telethon import TelegramClient

from config import API_HASH, API_ID, SESSION_NAME
from tg_utils import confirm, resolve_chat


async def main() -> None:
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--top", type=int, default=0, help="show only top N (default: all)")
    p.add_argument("--include-archived", action="store_true",
                   help="include archived dialogs (default: only normal)")
    p.add_argument("--mark-read", help="mark this specific chat as read")
    p.add_argument("--mark-all-read", action="store_true",
                   help="mark every unread chat as read (DESTRUCTIVE)")
    p.add_argument("--yes", "-y", action="store_true", help="skip confirmation")
    args = p.parse_args()

    archived = None if args.include_archived else False

    async with TelegramClient(SESSION_NAME, API_ID, API_HASH) as client:
        # Single-target mark-read
        if args.mark_read:
            entity = await resolve_chat(client, args.mark_read)
            await client.send_read_acknowledge(entity)
            title = getattr(entity, "title", None) or getattr(entity, "username", None) or str(entity.id)
            print(f"✓ {title} marked as read")
            return

        # Collect unread
        unread: list[tuple[int, str, int, bool]] = []
        async for d in client.iter_dialogs(archived=archived):
            if d.unread_count > 0:
                kind = "channel" if (d.is_channel and not d.is_group) else (
                    "group" if d.is_group else "user")
                unread.append((d.unread_count, d.name or str(d.id), d.id, d.is_channel))
                # store original Dialog for later mark-read pass
                unread[-1] = (d.unread_count, d.name or str(d.id), d.id, kind)

        unread.sort(reverse=True)
        if args.top:
            unread = unread[:args.top]

        total = sum(n for n, *_ in unread)
        print(f"# {len(unread)} unread chats — {total} unread messages\n")
        for n, name, cid, kind in unread:
            print(f"  {n:>5}  [{kind:<7}]  {name}  (id={cid})")

        # Mark-all-read
        if args.mark_all_read:
            print()
            if not args.yes and not confirm(f"Mark ALL {len(unread)} chats as read?"):
                print("iptal.")
                return
            for _, name, cid, _ in unread:
                try:
                    await client.send_read_acknowledge(await client.get_input_entity(cid))
                    print(f"  ✓ {name}")
                except Exception as e:
                    print(f"  ! {name}: {e}")


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