#!/usr/bin/env bash

set -euo pipefail

BASE_URL="${1:-https://explorer.d-bis.org}"

python3 - "$BASE_URL" <<'PY'
import re
import sys
import requests

base = sys.argv[1].rstrip("/")
session = requests.Session()
session.headers.update({"User-Agent": "ExplorerHealthCheck/1.0"})

checks = [
    "/",
    "/home",
    "/blocks",
    "/transactions",
    "/addresses",
    "/bridge",
    "/weth",
    "/tokens",
    "/pools",
    "/watchlist",
    "/more",
    "/analytics",
    "/operator",
    "/liquidity",
    "/snap/",
    "/docs.html",
    "/privacy.html",
    "/terms.html",
    "/acknowledgments.html",
    "/api/v2/stats",
    "/api/config/token-list",
    "/api/config/networks",
    "/explorer-api/v1/features",
    "/explorer-api/v1/ai/context?q=cUSDT",
    "/token-aggregation/api/v1/routes/tree?chainId=138&tokenIn=0x93E66202A11B1772E55407B32B44e5Cd8eda7f22&tokenOut=0x004b63A7B5b0E06f6bB6adb4a5F9f590BF3182D1&amountIn=1000000",
    "/token-aggregation/api/v1/routes/matrix",
    "/token-aggregation/api/v1/routes/ingestion?fromChainId=138&routeType=swap",
    "/token-aggregation/api/v1/routes/partner-payloads?partner=0x&amount=1000000&includeUnsupported=true",
]

failed = False

print("== Core routes ==")
for path in checks:
    url = base + path
    try:
        resp = session.get(url, timeout=20, allow_redirects=True)
        ctype = resp.headers.get("content-type", "")
        print(f"{resp.status_code:>3}  {path}  [{ctype[:50]}]")
        if resp.status_code >= 400:
            failed = True
    except Exception as exc:
        failed = True
        print(f"ERR  {path}  [{exc}]")

print("\n== Internal href targets from homepage ==")
try:
    home = session.get(base + "/", timeout=20).text
    hrefs = sorted(set(re.findall(r'href="([^"]+)"', home)))
    for href in hrefs:
        if href.startswith("/") and not href.startswith("//"):
            resp = session.get(base + href, timeout=20, allow_redirects=True)
            print(f"{resp.status_code:>3}  {href}")
            if resp.status_code >= 400:
                failed = True
except Exception as exc:
    failed = True
    print(f"ERR  homepage href sweep failed: {exc}")

print("\n== Static explorer domains referenced by bridge page ==")
external_roots = [
    "https://etherscan.io/",
    "https://bscscan.com/",
    "https://polygonscan.com/",
    "https://subnets.avax.network/c-chain",
    "https://basescan.org/",
    "https://arbiscan.io/",
    "https://optimistic.etherscan.io/",
]
for url in external_roots:
    try:
        resp = session.get(url, timeout=20, allow_redirects=True)
        print(f"{resp.status_code:>3}  {url}")
    except Exception as exc:
        print(f"ERR  {url}  [{exc}]")

if failed:
    sys.exit(1)
PY
