---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import json import re import tempfile from datetime import datetime, timezone from pathlib import Path from typing import Any BASE = Path(__file__).resolve().parent."
resource: "https://seo.copecheck.com"
tags: ["copecheck", "seo", "source-file", "py"]
timestamp: "2026-05-12T15:13:15Z"
site: "seo"
source_path: "copecheck-seo/sync_network_sites.py"
---

# from __future__ import annotations

Source path: `copecheck-seo/sync_network_sites.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-12T15:13:15Z`

```py
from __future__ import annotations

import argparse
import json
import re
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


BASE = Path(__file__).resolve().parent
DEFAULT_CONFIG = Path("/etc/cloudflared/config.yml")
DEFAULT_OUT = BASE / "data" / "network-sites.json"


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def canonical_host(host: str) -> str:
    host = host.strip().lower()
    if host == "copecheck.com":
        return "www.copecheck.com"
    return host


def label_for_host(host: str) -> str:
    if host == "www.copecheck.com":
        return "Main Oracle"
    subdomain = host.removesuffix(".copecheck.com")
    return subdomain.replace("-", " ").title()


def parse_cloudflared_hosts(config_path: Path) -> list[dict[str, str]]:
    text = config_path.read_text(encoding="utf-8")
    sites: list[dict[str, str]] = []
    current_host: str | None = None
    for raw_line in text.splitlines():
        host_match = re.match(r"\s*-\s*hostname:\s*([^\s#]+)", raw_line)
        if host_match:
            current_host = host_match.group(1).strip()
            continue
        service_match = re.match(r"\s*service:\s*([^\s#]+)", raw_line)
        if not service_match or not current_host:
            continue
        host = canonical_host(current_host)
        if host == "www.copecheck.com" or host.endswith(".copecheck.com"):
            sites.append(
                {
                    "host": host,
                    "url": f"https://{host}/",
                    "label": label_for_host(host),
                    "source": "cloudflared",
                    "service": service_match.group(1).strip(),
                }
            )
        current_host = None
    merged: dict[str, dict[str, str]] = {}
    for site in sites:
        existing = merged.get(site["host"], {})
        merged[site["host"]] = {**existing, **site}
    return sorted(merged.values(), key=lambda item: ("0" if item["host"] == "www.copecheck.com" else item["host"]))


def write_json_atomic(path: Path, data: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as handle:
        json.dump(data, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
        tmp_path = Path(handle.name)
    tmp_path.replace(path)


def main() -> None:
    parser = argparse.ArgumentParser(description="Sync CopeCheck public host registry from cloudflared config.")
    parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    args = parser.parse_args()

    sites = parse_cloudflared_hosts(args.config)
    write_json_atomic(
        args.out,
        {
            "generated_at": utc_now(),
            "source": str(args.config),
            "sites": sites,
        },
    )
    print(json.dumps({"ok": True, "sites": len(sites), "out": str(args.out)}, ensure_ascii=False))


if __name__ == "__main__":
    main()
```
