#!/usr/bin/env python3
"""Read recent posts from a public Telegram channel via its web preview —
no bot token, no MTProto auth. Only works for public channels."""
import argparse
import html
import json
import re
import urllib.request

parser = argparse.ArgumentParser()
parser.add_argument("channel", help="channel username, without @")
parser.add_argument("--limit", type=int, default=5)
args = parser.parse_args()

url = f"https://t.me/s/{args.channel}"
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
body = urllib.request.urlopen(req, timeout=15).read().decode("utf-8")

texts = re.findall(r'class="tgme_widget_message_text[^"]*"[^>]*>(.*?)</div>', body, re.S)
views = re.findall(r'tgme_widget_message_views">([^<]+)<', body)

posts = []
for text, view in zip(texts, views):
    clean = html.unescape(re.sub(r"<[^>]+>", " ", text))
    clean = re.sub(r"\s+", " ", clean).strip()
    posts.append({"channel": args.channel, "views": view, "text": clean})


def view_count(v):
    v = v.strip()
    mult = {"K": 1_000, "M": 1_000_000}.get(v[-1], 1)
    return float(v.rstrip("KM")) * mult if v[-1] in "KM" else float(v)


posts.sort(key=lambda p: -view_count(p["views"]))
print(json.dumps(posts[: args.limit], ensure_ascii=False, indent=2))
