from __future__ import annotations

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

from ..core.psl_root import registrable_root
from .company_to_domain import company_to_domain


def _email_root(email: str) -> str:
    try:
        domain = (email or "").split("@", 1)[1]
    except Exception:
        domain = ""
    return registrable_root(domain)


def _domain_candidate(value: str) -> str:
    raw = (value or "").strip()
    if not raw or "@" in raw:
        return ""
    candidate = raw
    if "://" not in candidate:
        candidate = f"http://{candidate}"
    try:
        parsed = urlparse(candidate)
    except Exception:
        return ""
    host = parsed.hostname or ""
    if not host or "." not in host:
        return ""
    return host.lower()


def email_domain_match(obj: Any) -> Dict[str, Any]:
    """
    Accepts either:
      - dict {"email": "...", "company": "...", "domain": optional explicit domain}
      - string email (and we just validate it has a domain)
    """
    if isinstance(obj, dict):
        email = obj.get("email", "")
        company = obj.get("company", "")
        dom = obj.get("domain", "") or _domain_candidate(company)
        if not dom and company:
            dom = company_to_domain(company)["value"].get("domain", "")
        left = _email_root(email)
        right = registrable_root(dom)
        return {"value": bool(left and right and left == right)}
    # string fallback: just check shape
    return {"value": bool(_email_root(str(obj)))}
