from __future__ import annotations

import re
from typing import Any, Dict, Tuple


_LOCAL_PART_RE = re.compile(r"^[A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]+$")
_DOMAIN_LABEL_RE = re.compile(r"^[A-Za-z0-9-]+$")


def _validate_email(value: Any) -> Tuple[bool, str]:
    email = str(value or "").strip()
    if not email:
        return False, "empty"
    at_count = email.count("@")
    if at_count == 0:
        return False, "missing_at"
    if at_count > 1:
        return False, "multiple_at"

    local, domain = email.split("@", 1)
    if not local:
        return False, "missing_local"
    if not domain:
        return False, "missing_domain"
    if local.startswith(".") or local.endswith(".") or ".." in local:
        return False, "invalid_local"
    if not _LOCAL_PART_RE.fullmatch(local):
        return False, "invalid_local"

    labels = domain.split(".")
    if len(labels) < 2:
        return False, "missing_tld"
    for label in labels:
        if not label:
            return False, "invalid_domain"
        if label.startswith("-") or label.endswith("-"):
            return False, "invalid_domain"
        if not _DOMAIN_LABEL_RE.fullmatch(label):
            return False, "invalid_domain"

    if len(labels[-1]) < 2:
        return False, "invalid_tld"
    return True, ""


def validate_email_syntax(value: Any) -> Dict[str, Any]:
    is_valid, reason = _validate_email(value)
    return {"value": [is_valid, reason]}
