#!/usr/bin/env python3
"""viewpage — read a web page as plain text.

A pocket copy of the house viewer on sec.matrix.
Prints the status, the final address, the page title,
and the words on the page with all the tags stripped out.

Use:  viewpage https://777software.net
      viewpage https://example.com 2000   (only show 2000 letters)
"""

import html
import re
import sys
import urllib.request

USER_AGENT = "777-viewpage/7.7 (iSH)"


def page_text(raw):
    """Pull the readable words out of a page of HTML."""
    raw = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", raw)
    raw = re.sub(r"(?s)<!--.*?-->", " ", raw)
    raw = re.sub(r"(?s)<[^>]+>", " ", raw)
    return " ".join(html.unescape(raw).split())


def page_title(raw):
    match = re.search(r"(?is)<title[^>]*>(.*?)</title>", raw)
    if not match:
        return "(no title)"
    return " ".join(html.unescape(match.group(1)).split())


def main():
    if len(sys.argv) < 2:
        print("Tell me a page to read.")
        print("Like this:  viewpage https://777software.net")
        return 1
    url = sys.argv[1]
    limit = int(sys.argv[2]) if len(sys.argv) > 2 else 4000

    request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    try:
        with urllib.request.urlopen(request, timeout=20) as page:
            status = page.status
            final_url = page.geturl()
            raw = page.read().decode("utf-8", errors="replace")
    except Exception as error:
        print("Could not read that page.")
        print("Reason:", error)
        return 1

    print("STATUS", status)
    print("URL", final_url)
    print("TITLE", page_title(raw))
    print("---")
    print(page_text(raw)[:limit])
    return 0


if __name__ == "__main__":
    sys.exit(main())
