#!/usr/bin/env python3
"""httpcode - fetch a URL and report status, time, size, and redirect chain.
Usage: httpcode URL [--selftest]
  One request (urllib, stdlib only) with a 10s timeout: final status code,
  total time, response size, content type, and every hop of the redirect
  chain with its status — the twist vs curl -I: the chain is the point, so
  a 301 -> 302 -> 200 shows as a story, not just the final 200.
"""
import argparse
import sys
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # raise HTTPError so we can record the hop ourselves


def fetch(url, timeout=10.0, max_hops=10):
    """Return (chain, final) where chain is [(url, status)] and final is a dict."""
    chain = []
    opener = urllib.request.build_opener(NoRedirect)
    current = url
    t0 = time.monotonic()
    final = {}
    for _ in range(max_hops + 1):
        req = urllib.request.Request(current, headers={"User-Agent": "httpcode/1.0"})
        try:
            with opener.open(req, timeout=timeout) as resp:
                body = resp.read()
                final = {"url": current, "status": resp.status,
                         "size": len(body), "ctype": resp.headers.get("Content-Type", ""),
                         "elapsed_ms": (time.monotonic() - t0) * 1000}
                chain.append((current, resp.status))
                return chain, final
        except urllib.error.HTTPError as e:
            chain.append((current, e.code))
            loc = e.headers.get("Location")
            if e.code in (301, 302, 303, 307, 308) and loc:
                current = urllib.parse.urljoin(current, loc)
                continue
            body = e.read() if hasattr(e, "read") else b""
            final = {"url": current, "status": e.code, "size": len(body),
                     "ctype": e.headers.get("Content-Type", ""),
                     "elapsed_ms": (time.monotonic() - t0) * 1000}
            return chain, final
        except urllib.error.URLError as e:
            final = {"url": current, "status": None, "size": 0, "ctype": "",
                     "elapsed_ms": (time.monotonic() - t0) * 1000, "error": str(e.reason)}
            return chain, final
    final = {"url": current, "status": None, "size": 0, "ctype": "",
             "elapsed_ms": (time.monotonic() - t0) * 1000, "error": "too many redirects"}
    return chain, final


def report(chain, final):
    print("redirect chain:")
    for i, (url, status) in enumerate(chain):
        print(f"  {i + 1}. {status}  {url}")
    if final.get("error"):
        print(f"FAILED: {final['error']} (after {final['elapsed_ms']:.0f} ms)")
        return 1
    print(f"final: {final['status']} in {final['elapsed_ms']:.0f} ms, "
          f"{final['size']} bytes, {final['ctype'] or '(no content-type)'}")
    return 0


def selftest():
    class H(BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == "/old":
                self.send_response(301)
                self.send_header("Location", "/new")
                self.end_headers()
            elif self.path == "/new":
                body = b"hello"
                self.send_response(200)
                self.send_header("Content-Type", "text/plain")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            else:
                self.send_response(404)
                self.end_headers()
        def log_message(self, *a):
            pass

    srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
    port = srv.server_address[1]
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    try:
        chain, final = fetch(f"http://127.0.0.1:{port}/old")
        print("selftest: local server with /old -> 301 -> /new (200)")
        rc = report(chain, final)
        assert [s for _, s in chain] == [301, 200], f"chain wrong: {chain}"
        assert final["status"] == 200 and final["size"] == 5, f"final wrong: {final}"
        print("selftest: redirect chain 301 -> 200 recorded, size 5 bytes — OK")
        return rc
    finally:
        srv.shutdown()


def main():
    ap = argparse.ArgumentParser(description="httpcode - fetch a URL and report status, time, size, and redirect chain")
    ap.add_argument("url", nargs="?", help="URL to fetch")
    ap.add_argument("--timeout", type=float, default=10.0, help="request timeout in seconds (default 10)")
    ap.add_argument("--selftest", action="store_true", help="fetch a local server with a 301 redirect")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if not args.url:
        ap.error("URL is required (or use --selftest)")
    chain, final = fetch(args.url, args.timeout)
    return report(chain, final)


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