from __future__ import annotations

import re
from typing import Any, Dict

from fmatch.core.heuristics import FREEMAIL_DOMAINS, TEMP_DOMAINS
from fmatch.core.normalization.domain import normalize_domain


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


def is_business_email(email: str) -> Dict[str, Any]:
    e = (email or "").strip().lower()
    if not _EMAIL_RX.match(e):
        return {"value": False, "meta": {"reason": "invalid_email"}}
    try:
        _local, domain = e.split("@", 1)
    except ValueError:
        return {"value": False, "meta": {"reason": "invalid_email"}}

    normalized_domain = normalize_domain(domain) or domain
    if normalized_domain in TEMP_DOMAINS:
        return {
            "value": False,
            "meta": {"reason": "temporary_domain", "domain": normalized_domain},
        }
    if normalized_domain in FREEMAIL_DOMAINS:
        return {
            "value": False,
            "meta": {"reason": "freemail_domain", "domain": normalized_domain},
        }
    return {
        "value": True,
        "meta": {"reason": "business_domain", "domain": normalized_domain},
    }
