#!/usr/bin/env python3
"""Link preview check: will these URLs show a large image card on X / Slack / Discord?

Usage: python3 check.py URL [URL ...]
Stdlib only. Fetches raw HTML like a crawler (no JavaScript), reads the
Open Graph / Twitter card tags, downloads the image header and measures it.
Exit code 1 if any URL has a problem marked "!" (warnings "~" don't fail).
Writes a Markdown table to $GITHUB_STEP_SUMMARY when it is set.
"""
import html as htmllib, os, re, struct, sys, urllib.error, urllib.request
from urllib.parse import urljoin

UA = "Mozilla/5.0 (compatible; Twitterbot/1.0)"


def fetch(url, limit=600_000, hops=5):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return r.geturl(), r.status, r.headers.get("content-type", ""), \
                int(r.headers.get("content-length") or 0), r.read(limit)
    except urllib.error.HTTPError as e:  # some Pythons don't follow 307/308
        if e.code in (301, 302, 307, 308) and hops and e.headers.get("Location"):
            return fetch(urljoin(url, e.headers["Location"]), limit, hops - 1)
        raise


def meta(html, key):
    for pat in (r'<meta[^>]+(?:property|name)=["\']%s["\'][^>]*content=["\']([^"\']*)',
                r'<meta[^>]+content=["\']([^"\']*)["\'][^>]*(?:property|name)=["\']%s["\']'):
        m = re.search(pat % re.escape(key), html, re.I)
        if m:
            return htmllib.unescape(m.group(1).strip())
    return None


def image_size(b):
    """(width, height) from the first bytes of a PNG/GIF/WebP/JPEG, 'svg', or None."""
    if b[:8] == b"\x89PNG\r\n\x1a\n" and len(b) >= 24:
        return struct.unpack(">II", b[16:24])
    if b[:6] in (b"GIF87a", b"GIF89a"):
        return struct.unpack("<HH", b[6:10])
    if b[:4] == b"RIFF" and b[8:12] == b"WEBP":
        c = b[12:16]
        if c == b"VP8 ":
            w, h = struct.unpack("<HH", b[26:30])
            return w & 0x3FFF, h & 0x3FFF
        if c == b"VP8L":
            v = int.from_bytes(b[21:25], "little")
            return (v & 0x3FFF) + 1, ((v >> 14) & 0x3FFF) + 1
        if c == b"VP8X":
            return int.from_bytes(b[24:27], "little") + 1, int.from_bytes(b[27:30], "little") + 1
    if b[:2] == b"\xff\xd8":
        i = 2
        while i + 9 < len(b):
            if b[i] != 0xFF:
                i += 1
                continue
            m = b[i + 1]
            if m in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
                h, w = struct.unpack(">HH", b[i + 5:i + 9])
                return w, h
            if m in (0xD8, 0x01) or 0xD0 <= m <= 0xD7:
                i += 2
                continue
            i += 2 + struct.unpack(">H", b[i + 2:i + 4])[0]
    if b"<svg" in b[:1000]:
        return "svg"
    return None


def check(url):
    """Return (tags, size, issues). issues = list of (level, text); level '!' fails, '~' warns."""
    final, status, _, _, body = fetch(url)
    html = body.decode("utf-8", "ignore")
    tags = {k: meta(html, k) for k in
            ("og:title", "og:description", "og:image", "twitter:card", "twitter:image")}
    issues, size = [], None
    img = tags["twitter:image"] or tags["og:image"]
    if not img:
        issues.append(("!", "no og:image / twitter:image in the raw HTML -> no image in the preview "
                            "(tags added by JavaScript are invisible to crawlers)"))
    if not tags["twitter:card"]:
        issues.append(("!", "no twitter:card -> X shows no large image card"))
    elif tags["twitter:card"] != "summary_large_image":
        issues.append(("~", f"twitter:card is '{tags['twitter:card']}' -> small thumbnail on X"))
    if not tags["og:title"]:
        issues.append(("~", "no og:title -> title falls back to <title> or the URL"))
    if img:
        iu = urljoin(final, img)
        if not iu.startswith("https://"):
            issues.append(("!", f"image URL is not https: {iu[:90]}"))
        if not re.match(r"https?://", img):
            issues.append(("~", "og:image is a relative URL; the spec wants an absolute one "
                                "(some crawlers ignore relative URLs)"))
        try:
            _, ist, ctype, clen, ib = fetch(iu, limit=64_000)
            size = image_size(ib)
            if ist != 200:
                issues.append(("!", f"image returns HTTP {ist}"))
            if "svg" in ctype or size == "svg":
                issues.append(("!", "image is SVG -> X/Slack/Discord don't render SVG previews; use PNG/JPG"))
            elif not ctype.startswith("image/"):
                issues.append(("!", f"image content-type is '{ctype}', not an image"))
            if clen >= 5_000_000:
                issues.append(("!", f"image is {clen // 1000} KB (X limit is 5 MB)"))
            elif clen > 1_000_000:
                issues.append(("~", f"image is {clen // 1000} KB - works, but slow in chat apps"))
            if isinstance(size, tuple) and tags["twitter:card"] != "summary":
                w, h = size
                r = w / h if h else 0
                if w < 300 or h < 157:
                    issues.append(("!", f"image is {w}x{h}; X needs at least 300x157 for a large card"))
                elif w < 1000:
                    issues.append(("~", f"image is {w}x{h}; looks blurry on retina screens (1200x630 recommended)"))
                if r and not 1.6 <= r <= 2.1:
                    issues.append(("~", f"aspect ratio {r:.2f}:1; X/Slack crop to about 1.91:1 (1200x630)"))
        except Exception as e:  # noqa: BLE001 - report any fetch error
            issues.append(("!", f"image fetch failed: {str(e)[:90]}"))
    return status, tags, size, issues


def main(urls):
    rows, failed = [], False
    for u in urls:
        try:
            status, tags, size, issues = check(u)
        except Exception as e:  # noqa: BLE001
            status, tags, size, issues = "-", {}, None, [("!", f"page fetch failed: {str(e)[:90]}")]
        print(f"\n{u}  (HTTP {status})")
        for k, v in tags.items():
            print(f"  {k:15} {v[:70] if v else '-'}")
        if isinstance(size, tuple):
            print(f"  {'image size':15} {size[0]}x{size[1]}")
        if not issues:
            print("  OK: large preview should work")
        for lvl, t in issues:
            print(f"  {lvl} {t}")
        bad = any(l == "!" for l, _ in issues)
        failed |= bad
        verdict = "fail" if bad else ("warn" if issues else "ok")
        sz = f"{size[0]}x{size[1]}" if isinstance(size, tuple) else (size or "-")
        rows.append((u, verdict, tags.get("twitter:card") or "-", sz,
                     "<br>".join(f"{l} {t}" for l, t in issues) or "-"))
    summary = os.environ.get("GITHUB_STEP_SUMMARY")
    if summary:
        with open(summary, "a", encoding="utf-8") as f:
            f.write("### Link preview check\n\n| URL | result | twitter:card | image | notes |\n"
                    "|---|---|---|---|---|\n")
            for r in rows:
                f.write("| " + " | ".join(str(c).replace("|", "\\|") for c in r) + " |\n")
    return 1 if failed else 0


if __name__ == "__main__":
    args = [a for a in sys.argv[1:] if a.strip()]
    if not args:
        sys.exit("usage: check.py URL [URL ...]")
    sys.exit(main(args))
