"""صفحه تست اتصال روی Python App هاست cPanel، بدون کتابخانه بیرونی.

فایل‌های این پوشه و connectivity_test.py باید در یک پوشه باشند.

آدرس‌ها:
    /?key=...                                   تست سریع
    /?key=...&section=upload                    ماتریس آپلود
    /?key=...&section=all                       همه
    /?key=...&format=json                       خروجی JSON
    &worker_url=https://name.sub.workers.dev    آدرس ورکر
    &timeout=20                                 مهلت هر تست
"""

import html
import json
import os
import sys
import time
import urllib.parse

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

try:
    import connectivity_test as ct
except Exception as exc:  # noqa: BLE001
    ct = None
    IMPORT_ERROR = "%s: %s" % (type(exc).__name__, exc)
else:
    IMPORT_ERROR = ""

ACCESS_KEY = "change-this-key"
WORKER_URL = ""
DEFAULT_TIMEOUT = 20
WEBAPP_VERSION = "2026-12-02-v2"


def response(start_response, status, body, content_type):
    payload = body.encode("utf-8")
    start_response(status, [
        ("Content-Type", content_type + "; charset=utf-8"),
        ("Content-Length", str(len(payload))),
        ("Cache-Control", "no-store"),
    ])
    return [payload]


def build_tests(worker, timeout, section):
    tests = {
        "dns": {
            "www.cloudflare.com": ct.resolve("www.cloudflare.com"),
            "generativelanguage.googleapis.com": ct.resolve("generativelanguage.googleapis.com"),
        },
        "cloudflare_edge": ct.call(ct.EDGE_URL, timeout=timeout),
        "google_gemini_direct": ct.call(
            ct.GOOGLE_URL, timeout=timeout, headers={"x-goog-api-key": "connectivity-test-invalid-key"}
        ),
    }

    if not worker:
        return tests

    host = urllib.parse.urlsplit(worker).hostname or "worker"
    tests["dns"][host] = ct.resolve(host)
    tests["worker_ping"] = ct.call(worker + "/ping", timeout=timeout)
    tests["worker_egress"] = ct.call(worker + "/egress", timeout=timeout)
    tests["worker_google"] = ct.call(worker + "/google?timeout_ms=30000", timeout=max(35, timeout))

    if section in ("upload", "all"):
        for size in ct.UPLOAD_MATRIX:
            tests["post_%d_bytes" % size] = ct.call(
                worker + "/echo",
                method="POST",
                payload=b"V" * size,
                headers={"content-type": "application/octet-stream", "content-length": str(size)},
                timeout=timeout,
            )
    else:
        tests["worker_upload_1mb"] = ct.call(
            worker + "/echo",
            method="POST",
            payload=b"V" * (1024 * 1024),
            headers={"content-type": "application/octet-stream", "content-length": str(1024 * 1024)},
            timeout=timeout,
        )

    return tests


def test_card(name, test):
    if not isinstance(test, dict) or "status" not in test:
        return "<h3>%s</h3><pre style='direction:ltr'>%s</pre>" % (
            html.escape(str(name)),
            html.escape(json.dumps(test, ensure_ascii=False, indent=2)),
        )
    ok = is_ok(name, test)
    color = "#2e7d5b" if ok else "#8d3a3a"
    parts = [
        "<div style='border:1px solid %s;border-radius:8px;padding:10px;margin:10px 0'>" % color,
        "<b>%s</b> — %s" % (html.escape(str(name)), "موفق" if ok else "ناموفق"),
        "<div style='color:#9aa4b2;font-size:13px'>status=%s · seconds=%s · payload=%s · error=%s</div>"
        % (test.get("status"), test.get("seconds"), test.get("payload_bytes"), html.escape(str(test.get("error")))),
    ]
    if test.get("body"):
        parts.append(
            "<pre style='direction:ltr;text-align:left;white-space:pre-wrap;background:#0b0d11;padding:8px;border-radius:6px'>%s</pre>"
            % html.escape(str(test.get("body"))[:900])
        )
    parts.append("</div>")
    return "".join(parts)


def is_ok(name, test):
    status = test.get("status") or 0
    if test.get("error"):
        return False
    if 200 <= status < 300:
        return True
    return name == "google_gemini_direct" and status in (400, 401, 403)


def render_html(section, worker, tests):
    checked = [(name, test) for name, test in tests.items() if isinstance(test, dict) and "status" in test]
    passed = [name for name, test in checked if is_ok(name, test)]
    failed = [name for name, test in checked if not is_ok(name, test)]
    body = [
        "<meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'>",
        "<title>تست اتصال هاست پایتون</title>",
        "<body style='font-family:Tahoma,system-ui;background:#0f1115;color:#e7e9ee;padding:24px;line-height:1.8'>",
        "<h2>تست اتصال از هاست پایتون</h2>",
        "<p style='color:#9aa4b2;font-size:13px'>نسخه: %s · نسخه ماژول تست: %s · User-Agent: %s</p>"
        % (WEBAPP_VERSION, getattr(ct, "VERSION", "قدیمی"), getattr(ct, "USER_AGENT", "پیش‌فرض پایتون")),
        "<p style='color:#9aa4b2'>worker: %s · section: %s · time: %s</p>"
        % (html.escape(worker or "تنظیم نشده"), html.escape(section), time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime())),
        "<p>موفق: %d · ناموفق: %d</p>" % (len(passed), len(failed)),
    ]
    for name, test in tests.items():
        body.append(test_card(name, test))
    body.append("</body>")
    return "".join(body)


def application(environ, start_response):
    params = urllib.parse.parse_qs(environ.get("QUERY_STRING", ""))
    if ACCESS_KEY and (params.get("key") or [""])[0] != ACCESS_KEY:
        return response(start_response, "403 Forbidden", "Forbidden. Add ?key=...", "text/plain")

    if ct is None:
        return response(
            start_response,
            "500 Internal Server Error",
            "connectivity_test.py در دسترس نیست: " + IMPORT_ERROR,
            "text/plain",
        )

    worker = (params.get("worker_url") or [WORKER_URL])[0].rstrip("/")
    timeout = int((params.get("timeout") or [DEFAULT_TIMEOUT])[0])
    section = (params.get("section") or ["quick"])[0]

    tests = build_tests(worker, timeout, section)
    if (params.get("format") or ["html"])[0] == "json":
        return response(start_response, "200 OK", json.dumps(tests, indent=2, ensure_ascii=False), "application/json")
    return response(start_response, "200 OK", render_html(section, worker, tests), "text/html")
