"""Project-facing wrapper around the vendor email runtime."""

from __future__ import annotations

import importlib.util
import os
import sys
from functools import lru_cache
from pathlib import Path
from types import ModuleType

_VENDOR_MODULE = "{{ rapidkit_vendor_module }}"
_VENDOR_VERSION = "{{ rapidkit_vendor_version }}"
_VENDOR_RELATIVE_PATH = "{{ vendor_runtime_relative }}"
_VENDOR_ROOT_ENV = "RAPIDKIT_VENDOR_ROOT"
_CACHE_PREFIX = "rapidkit_vendor_email"


def _project_root() -> Path:
    current = Path(__file__).resolve()
    for ancestor in current.parents:
        if (ancestor / "pyproject.toml").exists() or (ancestor / "package.json").exists():
            return ancestor
    return current.parents[5]


def _vendor_root() -> Path:
    override = os.getenv(_VENDOR_ROOT_ENV)
    if override:
        return Path(override).expanduser().resolve()
    return _project_root() / ".rapidkit" / "vendor"


def _vendor_base_dir() -> Path:
    root = _vendor_root()
    module_dir = root / _VENDOR_MODULE
    preferred = module_dir / _VENDOR_VERSION if _VENDOR_VERSION else None
    if preferred and preferred.exists():
        return preferred
    candidates = sorted((p for p in module_dir.glob("*") if p.is_dir()), reverse=True)
    if candidates:
        return candidates[0]
    raise RuntimeError(
        "RapidKit vendor payload for '{module}' not found under {root}. "
        "Re-run `rapidkit modules install {module}`.".format(module=_VENDOR_MODULE, root=root)
    )


def _vendor_file() -> Path:
    if not _VENDOR_RELATIVE_PATH:
        raise RuntimeError("Email vendor runtime relative path missing from generator context")
    return _vendor_base_dir() / _VENDOR_RELATIVE_PATH


@lru_cache(maxsize=1)
def _load_vendor_module() -> ModuleType:
    vendor_path = _vendor_file()
    if not vendor_path.exists():
        raise RuntimeError(
            "RapidKit vendor email runtime missing at {path}. "
            "Re-run `rapidkit modules install {module}`.".format(
                path=vendor_path,
                module=_VENDOR_MODULE,
            )
        )

    module_name = _CACHE_PREFIX + _VENDOR_MODULE.replace("/", "_")
    spec = importlib.util.spec_from_file_location(module_name, vendor_path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to load vendor email runtime from {vendor_path}")

    module = importlib.util.module_from_spec(spec)
    sys.modules.setdefault(module_name, module)
    spec.loader.exec_module(module)
    return module


def _resolve_export(name: str):
    module = _load_vendor_module()
    try:
        return getattr(module, name)
    except AttributeError as exc:  # pragma: no cover - defensive guard
        raise RuntimeError(f"Vendor email runtime missing attribute '{name}'") from exc


def refresh_vendor_module() -> None:
    """Clear import caches (useful after upgrading vendor payloads)."""

    _load_vendor_module.cache_clear()


AttachmentPayload = _resolve_export("AttachmentPayload")
EmailAttachment = _resolve_export("EmailAttachment")
EmailConfig = _resolve_export("EmailConfig")
EmailDeliveryError = _resolve_export("EmailDeliveryError")
EmailMessagePayload = _resolve_export("EmailMessagePayload")
EmailSendResult = _resolve_export("EmailSendResult")
EmailService = _resolve_export("EmailService")
EmailSettings = _resolve_export("EmailSettings")
EmailTemplateRenderer = _resolve_export("EmailTemplateRenderer")
SMTPSettings = _resolve_export("SMTPSettings")
TemplateSettings = _resolve_export("TemplateSettings")
describe_email = _resolve_export("describe_email")
get_email_metadata = _resolve_export("get_email_metadata")
list_email_features = _resolve_export("list_email_features")
get_email_service = _resolve_export("get_email_service")
register_email_service = _resolve_export("register_email_service")


try:  # Optional override contracts
    from core.services.override_contracts import apply_module_overrides
except ImportError:  # pragma: no cover - override system optional
    apply_module_overrides = None

if apply_module_overrides is not None:  # pragma: no branch - tiny guard
    apply_module_overrides(sys.modules[__name__], "communication/email")


__all__ = [
    "AttachmentPayload",
    "EmailAttachment",
    "EmailConfig",
    "EmailDeliveryError",
    "EmailMessagePayload",
    "EmailSendResult",
    "EmailService",
    "EmailSettings",
    "EmailTemplateRenderer",
    "SMTPSettings",
    "TemplateSettings",
    "describe_email",
    "get_email_metadata",
    "list_email_features",
    "get_email_service",
    "register_email_service",
    "refresh_vendor_module",
]
