from __future__ import annotations

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

from ..core.psl_root import registrable_root

_EMAIL_RX = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


def _email_domain(value: str) -> str:
    candidate = (value or "").strip()
    if not _EMAIL_RX.match(candidate):
        return ""
    return candidate.rsplit("@", 1)[1].lower()


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

    if s.lower().startswith("mailto:"):
        domain = _email_domain(s[7:])
        return {"value": registrable_root(domain) if domain else ""}

    # Treat only syntactically valid emails as emails. Malformed email-like
    # inputs should fail closed instead of being reinterpreted as URL auth.
    if "@" in s and "://" not in s:
        domain = _email_domain(s)
        return {"value": registrable_root(domain) if domain else ""}

    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)}
