"""Search messages — globally or scoped to one chat.

Usage:
    python tg_search.py "CVE-2024"                   # global, last 50 hits
    python tg_search.py "kitap" --chat "E Kitap"    # scoped to one chat
    python tg_search.py "Putin" --since 2026-04-01 --limit 100
    python tg_search.py "report" --chat me           # only Saved Messages

Global search uses Telegram's server-side message index (telethon
client.iter_messages(None, search=...)).
"""
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 fmt_msg, parse_date, resolve_chat


async def main() -> None:
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("query", help="search text")
    p.add_argument("--chat", help="restrict to this chat (@user/id/name/me)")
    p.add_argument("--limit", "-n", type=int, default=50)
    p.add_argument("--since", help="YYYY-MM-DD lower bound")
    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:
        if args.chat:
            entity = await resolve_chat(client, "me" if args.chat in {"me", "self"} else args.chat)
        else:
            entity = None

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

        # Cache chat titles to annotate global hits.
        chat_titles: dict[int, str] = {}

        async def title_for(chat_id: int) -> str:
            if chat_id in chat_titles:
                return chat_titles[chat_id]
            try:
                e = await client.get_entity(chat_id)
                t = getattr(e, "title", None) or getattr(e, "username", None) or str(chat_id)
            except Exception:
                t = str(chat_id)
            chat_titles[chat_id] = t
            return t

        count = 0
        async for msg in client.iter_messages(entity, **kwargs):
            count += 1
            if entity is None:
                where = await title_for(msg.peer_id.channel_id) if hasattr(msg.peer_id, "channel_id") \
                    else await title_for(getattr(msg.peer_id, "user_id", 0) or getattr(msg.peer_id, "chat_id", 0))
                print(f"[{where[:25]:<25}] {fmt_msg(msg)}")
            else:
                print(fmt_msg(msg))

        print(f"\n{count} hit(s)")


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