"""Read messages from a Telegram chat.

Usage:
    python tg_read.py "@username"
    python tg_read.py "Born2beroot" --limit 50
    python tg_read.py -1001182095274 --since 2026-04-01
    python tg_read.py "@durov" --limit 5 --json
"""
from __future__ import annotations

import argparse
import asyncio
import json

from telethon import TelegramClient

from config import API_HASH, API_ID, SESSION_NAME
from tg_utils import fmt_msg, parse_date, resolve_chat


async def main() -> None:
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("chat", help="@username, numeric id, or name substring")
    p.add_argument("--limit", "-n", type=int, default=20, help="max messages (default 20)")
    p.add_argument("--since", help="YYYY-MM-DD; only newer than this date")
    p.add_argument("--search", "-s", help="filter to messages containing this text")
    p.add_argument("--json", action="store_true", help="emit JSON instead of table")
    p.add_argument("--mark-read", action="store_true", help="mark fetched messages as read")
    args = p.parse_args()

    offset_date = parse_date(args.since) if args.since else None

    async with TelegramClient(SESSION_NAME, API_ID, API_HASH) as client:
        entity = await resolve_chat(client, args.chat)
        title = getattr(entity, "title", None) or getattr(entity, "username", None) or str(entity.id)

        if not args.json:
            print(f"# {title}  (id={entity.id})\n")

        kwargs = {"limit": args.limit}
        if offset_date:
            kwargs["reverse"] = True
            kwargs["offset_date"] = offset_date
        if args.search:
            kwargs["search"] = args.search

        rows = []
        async for msg in client.iter_messages(entity, **kwargs):
            if args.json:
                rows.append({
                    "id": msg.id,
                    "date": msg.date.isoformat(),
                    "sender_id": msg.sender_id,
                    "text": msg.message or "",
                    "has_media": msg.media is not None,
                    "reply_to": msg.reply_to_msg_id,
                })
            else:
                print(fmt_msg(msg))

        if args.json:
            print(json.dumps(rows, ensure_ascii=False, indent=2))

        if args.mark_read:
            await client.send_read_acknowledge(entity)
            if not args.json:
                print(f"\n✓ {title} marked as read")


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