"""
Core fuzzy matching functionality.

This module provides:
1. Matching engine (FuzzyMatcher, MatchConfig, etc.) - lazy loaded
2. Shared types (CompanyProfile, ResolutionResult, etc.)
3. Heuristics data (LEGAL_SUFFIXES, state maps, etc.)
4. PSL utilities (registrable_root)
5. Resolution (CompanyDomainResolver, resolve_company_domain, etc.)
6. Normalization (pure text normalization, no LLM)
7. Registry (DomainFamilyRegistry for company lookups)
8. FoundryGraph (HTTP client for company enrichment)
9. HTTP (BaseHTTPClient with retry and error handling)
10. LLM (BaseLLMProvider interface for AI operations)
"""

from __future__ import annotations

import logging
from typing import Any

log = logging.getLogger(__name__)

# =============================================================================
# Eager imports: Types, heuristics, PSL (no saas dependencies)
# =============================================================================
from .types import (
    CompanyProfile,
    ResolutionResult,
    ResolverMetrics,
    CircuitBreaker,
    IFoundryGraphClient,
    ILLMProvider,
    IRegistryDataSource,
    CoreError,
    ResolutionError,
    ValidationError,
)

from .psl import registrable_root

from .resolution import (
    CompanyDomainResolver,
    resolve_company_domain,
    resolve_company_domains,
    generate_domain_candidates,
    probe_domain_dns,
    validate_domain_dns,
    find_valid_domain_candidate,
    predict_domain_with_llm,
)

from .normalization import (
    normalize_text,
    normalize_company_text,
    title_case_tokens,
    normalize_title_text,
    classify_title_seniority,
    classify_title_department,
    normalize_country,
    normalize_state,
    map_state_code,
    map_state_name_to_code,
    normalize_domain,
)

from .registry import (
    DomainFamilyRegistry,
    DomainRelation,
)

from .foundrygraph import (
    FoundryGraphClient,
    FoundryGraphConfig,
    FoundryGraphError,
)

from .http import (
    BaseHTTPClient,
    RetryConfig,
    HTTPError,
    AuthenticationError,
    RateLimitError,
    TransientError,
)

from .llm import (
    BaseLLMProvider,
    LLMResponse,
    LLMError,
)

# =============================================================================
# Lazy imports: Engine/Matcher components (have saas dependencies)
# These are loaded on first access to avoid import-time saas loading.
# =============================================================================
_LAZY_EXPORTS = {
    # From matcher.py (has preprocessing deps that import saas)
    "FuzzyMatcher",
    # From engine.py (directly imports saas.worker_pool)
    "MatchConfig",
    "DedupeConfig",
    "BlockingMode",
    "BlockingWeightProfile",
    "process_dataframe",
    "make_blocking_column",
    "determine_optimal_blocking_strategy",
    "build_match_config",
    "build_dedupe_config",
    "DEFAULT_NORMALIZATION_RULES",
    "AVAILABLE_RULESETS",
    "detect_encoding",
    "decide_processing_mode",
    "_sanitize_name",
}

_lazy_cache: dict[str, Any] = {}


def __getattr__(name: str) -> Any:
    """Lazy load engine/matcher components on first access."""
    if name in _LAZY_EXPORTS:
        if name not in _lazy_cache:
            if name == "FuzzyMatcher":
                from . import matcher
                _lazy_cache[name] = getattr(matcher, name)
            else:
                from . import engine
                _lazy_cache[name] = getattr(engine, name)
        return _lazy_cache[name]
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


__all__ = [
    # Matching engine (lazy loaded)
    "FuzzyMatcher",
    "MatchConfig",
    "DedupeConfig",
    "BlockingMode",
    "BlockingWeightProfile",
    "process_dataframe",
    "make_blocking_column",
    "determine_optimal_blocking_strategy",
    "build_match_config",
    "build_dedupe_config",
    "DEFAULT_NORMALIZATION_RULES",
    "AVAILABLE_RULESETS",
    "detect_encoding",
    "decide_processing_mode",
    "_sanitize_name",
    # Shared types (eager)
    "CompanyProfile",
    "ResolutionResult",
    "ResolverMetrics",
    "CircuitBreaker",
    # Interfaces (eager)
    "IFoundryGraphClient",
    "ILLMProvider",
    "IRegistryDataSource",
    # Errors (eager)
    "CoreError",
    "ResolutionError",
    "ValidationError",
    # PSL utilities (eager)
    "registrable_root",
    # Resolution (eager - no saas deps at import time)
    "CompanyDomainResolver",
    "resolve_company_domain",
    "resolve_company_domains",
    "generate_domain_candidates",
    "probe_domain_dns",
    "validate_domain_dns",
    "find_valid_domain_candidate",
    "predict_domain_with_llm",
    # Normalization (eager - pure text processing)
    "normalize_text",
    "normalize_company_text",
    "title_case_tokens",
    "normalize_title_text",
    "classify_title_seniority",
    "classify_title_department",
    "normalize_country",
    "normalize_state",
    "map_state_code",
    "map_state_name_to_code",
    "normalize_domain",
    # Registry (eager - no saas deps)
    "DomainFamilyRegistry",
    "DomainRelation",
    # FoundryGraph (eager - HTTP client only)
    "FoundryGraphClient",
    "FoundryGraphConfig",
    "FoundryGraphError",
    # HTTP utilities (eager - no external deps)
    "BaseHTTPClient",
    "RetryConfig",
    "HTTPError",
    "AuthenticationError",
    "RateLimitError",
    "TransientError",
    # LLM interface (eager - abstract base only)
    "BaseLLMProvider",
    "LLMResponse",
    "LLMError",
]
