#!/usr/bin/env python3
"""Read-only RRE public-entry check using an honest descriptive client identity.

Run: python3 rre-public-access-check.py
No credentials, cookies, personal details, private APIs, form writes or packages.
This is not a browser, account sign-in test or mainland-China certification.
"""
import datetime
import json
import sys
import urllib.error
import urllib.request
from urllib.parse import urlsplit

USER_AGENT = "RRE-PublicAccess-Check/1.0 (+https://redrooenergy.com.au/support/contact/)"
PUBLIC_URLS = (
    "https://redrooenergy.com.au/",
    "https://redrooenergy.com.au/suppliers/portal/",
    "https://redrooenergy.com.au/suppliers/practice/",
    "https://redrooenergy.com.au/zh-cn/suppliers/portal/",
    "https://products.redrooenergy.com.au/",
    "https://products.redrooenergy.com.au/account/",
    "https://supplier.redrooenergy.com.au/",
    "https://supplier.redrooenergy.com.au/supplier-start/?view=apply",
    "https://rre.portal.redrooenergy.com.au/",
    "https://rre-installers-test.kenscottsas.chatgpt.site/register/",
)

class PublicRedirects(urllib.request.HTTPRedirectHandler):
    """Support canonical 308 redirects on Python 3.9 and keep checks on RRE."""
    def http_error_308(self, request, response, code, message, headers):
        # urllib in older Python versions omits 308; GET semantics match 307.
        return self.http_error_302(request, response, 307, message, headers)

    def redirect_request(self, request, response, code, message, headers, new_url):
        target = urlsplit(new_url)
        allowed = {urlsplit(url).hostname for url in PUBLIC_URLS}
        if target.scheme != "https" or target.hostname not in allowed:
            raise urllib.error.HTTPError(new_url, code, "Redirect outside public RRE hosts refused", headers, response)
        return super().redirect_request(request, response, code, message, headers, new_url)

OPENER = urllib.request.build_opener(PublicRedirects())

def check(url):
    request = urllib.request.Request(url, headers={
        "User-Agent": USER_AGENT,
        "Accept": "text/html,application/json;q=0.9,*/*;q=0.8",
    })
    row = {"url": url, "observedUtc": datetime.datetime.now(datetime.timezone.utc).isoformat()}
    try:
        with OPENER.open(request, timeout=30) as response:
            row.update(status=response.status, finalUrl=response.url,
                       rayId=response.headers.get("CF-Ray"),
                       contentType=response.headers.get("Content-Type"))
            # Bounded read exercises the response without saving customer data or cookies.
            row["receivedBytesUpTo4096"] = len(response.read(4096))
    except urllib.error.HTTPError as error:
        row.update(status=error.code, rayId=error.headers.get("CF-Ray"), error="HTTP request refused")
        error.close()
    except (urllib.error.URLError, TimeoutError, OSError) as error:
        row.update(status=None, error=type(error).__name__)
    return row

def main():
    rows = [check(url) for url in PUBLIC_URLS]
    print(json.dumps({"client": USER_AGENT, "scope": "Public transport only; no sign-in or form submission", "results": rows}, indent=2))
    return 0 if all(row.get("status") == 200 for row in rows) else 1

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