"""Server-side checks for one confirmed endpoint. A mismatch fails closed."""

from __future__ import annotations

from typing import Any
from urllib.parse import urlparse

from src.domain.adopt.contract import DEPLOYMENT_WELL_KNOWN_PATH


def assess_endpoint(
    *,
    expected_deployment_id: str,
    origin: str,
    reachable: bool,
    routes_respond: bool,
    tls_valid: bool,
    redirects_valid: bool,
    session_ok: bool,
    http_status: int,
    document: dict[str, Any] | None,
    production: bool = False,
    production_data_confirmed: bool = False,
) -> dict[str, Any]:
    """Classify observations. This function does not perform I/O."""
    reasons: list[str] = []
    if not reachable:
        reasons.append("origin_unreachable")
    if not routes_respond:
        reasons.append("routes_unresponsive")
    if _stale(origin):
        reasons.append("stale_origin")
    if not tls_valid or not str(origin).startswith("https://"):
        reasons.append("tls_invalid")
    if not redirects_valid:
        reasons.append("redirect_invalid")
    if not session_ok:
        reasons.append("session_failed")
    if production and not production_data_confirmed:
        reasons.append("production_unconfirmed")
    if not _deployment_matches(expected_deployment_id, http_status, document):
        reasons.append("deployment_mismatch")
    return {
        "ok": not reasons,
        "reasons": reasons,
        "well_known_path": DEPLOYMENT_WELL_KNOWN_PATH,
    }


def _deployment_matches(expected: str, http_status: int, document: dict[str, Any] | None) -> bool:
    if http_status != 200 or not isinstance(document, dict):
        return False
    found = document.get("deployment_id")
    return bool(expected) and found == expected


def _stale(origin: str) -> bool:
    host = (urlparse(origin).hostname or "").lower()
    return host in {"localhost", "127.0.0.1", "0.0.0.0", "::1"} or host.endswith(".local") or host.endswith(".test")
