#!/usr/bin/env python3
"""README first-impression checker (stdlib only).
Usage: python3 readme_check.py <README.md path or raw URL>
Flags what a first-time visitor misses: one-line pitch, install, usage example,
visual, license, link density, length of intro before first code block."""
import os, re, sys, urllib.request

def load(src):
    if src.startswith("http"):
        req = urllib.request.Request(src, headers={"User-Agent": "readme-check/0.1"})
        return urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "replace")
    return open(src, encoding="utf-8", errors="replace").read()

def has_license_file(src):
    names = ("LICENSE", "LICENSE.txt", "LICENSE.md", "LICENSE.rst", "COPYING")
    if src.startswith("http"):
        base = src.rsplit("/", 1)[0]
        for n in names:
            try:
                req = urllib.request.Request(base + "/" + n, method="HEAD", headers={"User-Agent": "readme-check/0.3"})
                if urllib.request.urlopen(req, timeout=10).status == 200:
                    return True
            except Exception:
                pass
        return False
    d = os.path.dirname(os.path.abspath(src))
    return any(os.path.exists(os.path.join(d, n)) for n in names)

def check(md, license_file=False):
    lines = md.splitlines()
    fenced, prose = False, []
    for l in lines:  # v0.2: ignore "# comments" inside ``` code fences
        if l.startswith("```"):
            fenced = not fenced
        prose.append(not fenced and not l.startswith("```"))
    heads = [l.strip("# ").lower() for l, ok in zip(lines, prose) if ok and l.startswith("#")]
    text_lines = [l for l in lines if l.strip() and not l.startswith(("#", "!", "[!", "<", "|", "```", "    "))]
    first_para = next((l for l in text_lines if len(l.split()) >= 5), "")
    code_idx = next((i for i, l in enumerate(lines) if l.startswith("```")), None)
    flags = []
    if not first_para:
        flags.append("No plain-sentence pitch near the top (visitor can't tell what it does)")
    elif len(first_para.split()) > 40:
        flags.append(f"First sentence/paragraph is long ({len(first_para.split())} words); aim for <25")
    # v0.3 (DEV comment by skepagent/amintacccp): a link to install docs counts as an install path
    install_link = re.search(r"\[[^\]]*(install|getting started|quick ?start)[^\]]*\]\(|\]\([^)]*(install|quickstart|getting-started)[^)]*\)", md, re.I)
    if not any(re.search(r"install|getting started|quick ?start|setup", h) for h in heads) and not re.search(r"\b(pip|npm|cargo|go|brew|yarn|pnpm) (install|add|get)\b", md) and not install_link:
        flags.append("No install / quick start section or install command")
    if code_idx is None:
        flags.append("No code block (no copy-paste usage example)")
    elif code_idx > 40:
        flags.append(f"First code example appears late (line {code_idx+1})")
    if not re.search(r"!\[[^\]]*\]\([^)]+\.(png|jpe?g|gif|svg|webp)", md, re.I) and "<img" not in md.lower():
        flags.append("No screenshot/GIF/diagram")
    # v0.3: a LICENSE file in the repo matters more than a README mention
    if not re.search(r"licen[sc]e", md, re.I) and not license_file:
        flags.append("No license mention")
    links = len(re.findall(r"\]\(http", md))
    badges = len(re.findall(r"img\.shields\.io|badge", md, re.I))
    if badges > 8:
        flags.append(f"Badge wall ({badges} badges) pushes the pitch down")
    return {"pitch": first_para[:160], "headings": heads[:12], "first_code_line": (code_idx + 1) if code_idx is not None else None,
            "links": links, "badges": badges, "flags": flags}

if __name__ == "__main__":
    r = check(load(sys.argv[1]), has_license_file(sys.argv[1]))
    print("Pitch:", r["pitch"] or "-")
    print("Headings:", ", ".join(r["headings"]) or "-")
    print("First code block line:", r["first_code_line"], "| links:", r["links"], "| badges:", r["badges"])
    print("Flags:" if r["flags"] else "Flags: none")
    for f in r["flags"]:
        print(" -", f)
