from __future__ import annotations

from typing import Any, Dict
from urllib.parse import urlparse

from ..core.psl_root import registrable_root


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

    # If it looks like an email, extract domain from after the @
    if "@" in s and not s.startswith("http"):
        parts = s.split("@")
        if len(parts) == 2 and "." in parts[1]:
            return {"value": registrable_root(parts[1].lower())}

    host = s
    if "://" not in s:
        s = "http://" + s
    try:
        parsed = urlparse(s)
        host = parsed.hostname or ""
    except Exception:
        pass
    return {"value": registrable_root(host)}
