from __future__ import annotations

import re
from typing import Any, Dict
from urllib.parse import urlsplit


_UNSUPPORTED_SCHEMES = {"mailto", "tel", "javascript", "data"}
_HAS_SCHEME_RE = re.compile(r"^[a-z][a-z0-9+.-]*:", re.IGNORECASE)


def _looks_like_invalid_host(host: str) -> bool:
    return (not host) or any(ch.isspace() for ch in host)


def clean_website(value: str) -> Dict[str, Any]:
    raw = (value or "").strip()
    if not raw:
        return {"value": ""}

    if _HAS_SCHEME_RE.match(raw) and "://" not in raw:
        scheme = raw.split(":", 1)[0].lower()
        if scheme in _UNSUPPORTED_SCHEMES:
            return {"value": ""}

    candidate = raw if "://" in raw else f"http://{raw}"
    try:
        parsed = urlsplit(candidate)
    except Exception:
        return {"value": raw}

    host = (parsed.hostname or "").lower()
    if _looks_like_invalid_host(host):
        return {"value": raw}

    path = (parsed.path or "/").rstrip("/")
    out = host if path in ("", "/") else f"{host}{path}"
    return {"value": out}
