"""Send a message (text and/or file) to a Telegram chat.

Usage:
    python tg_send.py "@username" "Hello"
    python tg_send.py "Born2beroot" "Check this" --file report.pdf
    python tg_send.py "@chan" "" --file image.png --caption "screenshot"
    python tg_send.py "Saved Messages" "note to self" --yes
    python tg_send.py "@x" "Reply" --reply-to 12345
    python tg_send.py "@x" "Quiet ping" --silent

Defaults to dry-run preview + interactive [y/N] confirm. --yes skips it.
Saved Messages is resolvable as "me" or by your own username.
"""
from __future__ import annotations

import argparse
import asyncio
import sys
from pathlib import Path

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("chat", help='@username, id, name; "me" for Saved Messages')
    p.add_argument("text", help="message text (use '' if only sending a file)")
    p.add_argument("--file", "-f", help="path to file/image to attach")
    p.add_argument("--caption", help="caption for the file (overrides text if --file given)")
    p.add_argument("--reply-to", type=int, help="message id to reply to")
    p.add_argument("--silent", action="store_true", help="send without notification")
    p.add_argument("--parse", choices=["md", "html", "none"], default="md",
                   help="text parse mode (default: md)")
    p.add_argument("--yes", "-y", action="store_true", help="skip confirmation")
    args = p.parse_args()

    if not args.text and not args.file:
        sys.exit("nothing to send: provide text and/or --file")

    if args.file and not Path(args.file).exists():
        sys.exit(f"file not found: {args.file}")

    parse_mode = None if args.parse == "none" else args.parse

    async with TelegramClient(SESSION_NAME, API_ID, API_HASH) as client:
        entity = await resolve_chat(client, "me" if args.chat in {"me", "self"} else args.chat)
        title = getattr(entity, "title", None) or getattr(entity, "username", None) or str(entity.id)

        print(f"→ to:    {title}  (id={entity.id})")
        if args.file:
            print(f"→ file:  {args.file}")
            print(f"→ cap:   {(args.caption or args.text)[:120]}")
        else:
            preview = args.text if len(args.text) < 200 else args.text[:200] + "…"
            print(f"→ text:  {preview}")
        if args.reply_to:
            print(f"→ reply: msg #{args.reply_to}")
        if args.silent:
            print("→ silent: yes")

        if not args.yes and not confirm("Gönder?"):
            print("iptal.")
            return

        if args.file:
            sent = await client.send_file(
                entity,
                args.file,
                caption=args.caption or args.text or None,
                reply_to=args.reply_to,
                silent=args.silent,
                parse_mode=parse_mode,
            )
        else:
            sent = await client.send_message(
                entity,
                args.text,
                reply_to=args.reply_to,
                silent=args.silent,
                parse_mode=parse_mode,
            )

        print(f"✓ sent msg id={sent.id}")


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