---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 from __future__ import annotations import argparse import json import re import sys from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import urlparse from."
resource: "https://corporate.copecheck.com"
tags: ["copecheck", "corporate", "source-file", "py"]
timestamp: "2026-05-19T00:39:06Z"
site: "corporate"
source_path: "copecheck-corporate/tools/audit_routes.py"
---

# !/usr/bin/env python3

Source path: `copecheck-corporate/tools/audit_routes.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-19T00:39:06Z`

```py
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen


BASE = Path(__file__).resolve().parents[1]
DATA_FILE = BASE / "data" / "reports.json"


def fetch_status(url: str, timeout: int = 20) -> tuple[int | str, str]:
    try:
        req = Request(url, headers={"User-Agent": "CopeCheck corporate route audit"})
        with urlopen(req, timeout=timeout) as response:
            response.read(256)
            return response.status, response.headers.get("content-type", "")
    except HTTPError as exc:
        return exc.code, "HTTPError"
    except (URLError, TimeoutError, OSError) as exc:
        return "ERR", f"{type(exc).__name__}: {exc}"


def generated_paths(data: dict) -> list[str]:
    paths = ["/", "/healthz", "/feed.json", "/llms.txt", "/sitemap.xml", "/robots.txt"]
    paths.extend(f"/company/{company['slug']}" for company in data.get("companies", []))
    paths.extend(f"/r/{report['id']}" for report in data.get("reports", []))
    seen: set[str] = set()
    return [path for path in paths if not (path in seen or seen.add(path))]


def load_data(base_url: str, data_file: Path) -> dict:
    if base_url.startswith("http://127.0.0.1") or base_url.startswith("http://localhost"):
        return json.loads(data_file.read_text(encoding="utf-8"))
    req = Request(base_url.rstrip("/") + "/feed.json", headers={"User-Agent": "CopeCheck corporate route audit"})
    with urlopen(req, timeout=20) as response:
        return json.loads(response.read().decode("utf-8"))


def sitemap_paths(base_url: str) -> set[str]:
    req = Request(base_url.rstrip("/") + "/sitemap.xml", headers={"User-Agent": "CopeCheck corporate route audit"})
    with urlopen(req, timeout=20) as response:
        xml = response.read().decode("utf-8", "ignore")
    paths = set()
    for loc in re.findall(r"<loc>(.*?)</loc>", xml):
        parsed = urlparse(loc)
        if parsed.path:
            paths.add(parsed.path)
    return paths


def main() -> int:
    parser = argparse.ArgumentParser(description="Audit Corporate Cope generated routes")
    parser.add_argument("--base", default="https://corporate.copecheck.com", help="Base URL to audit")
    parser.add_argument("--data", default=str(DATA_FILE), help="Local reports JSON for localhost audits")
    args = parser.parse_args()

    base_url = args.base.rstrip("/")
    data = load_data(base_url, Path(args.data))
    paths = generated_paths(data)
    failures: list[tuple[str, int | str, str]] = []

    for path in paths:
        status, detail = fetch_status(base_url + path)
        if status != 200:
            failures.append((path, status, detail))

    sitemap_missing: list[str] = []
    try:
        sitemap = sitemap_paths(base_url)
        expected = {path for path in paths if path not in {"/healthz", "/feed.json", "/llms.txt", "/robots.txt", "/sitemap.xml"}}
        sitemap_missing = sorted(expected - sitemap)
    except Exception as exc:
        failures.append(("/sitemap.xml", "ERR", f"{type(exc).__name__}: {exc}"))

    print(f"base={base_url}")
    print(f"companies={len(data.get('companies', []))} reports={len(data.get('reports', []))} routes={len(paths)}")
    print(f"route_failures={len(failures)} sitemap_missing={len(sitemap_missing)}")
    for path, status, detail in failures[:40]:
        print(f"FAIL {path} {status} {detail}")
    for path in sitemap_missing[:40]:
        print(f"SITEMAP_MISSING {path}")
    return 1 if failures or sitemap_missing else 0


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