"""Explicit comparison-only API, not registered with Flask or InvestmentManager."""
from contextlib import contextmanager
from threading import RLock

from . import runtime_paths
from .runtime_paths import LocalInputs

_generation_lock = RLock()


@contextmanager
def _environment(inputs):
    # The source packager/gateway use module globals. Serialize isolated calls
    # and give each run its own asset cache; restore them even on validation error.
    from . import export_packaging
    from .portals import workflows
    from .portals.otodom import dictionaries as od
    from .portals.domiporta import dictionaries as dp
    from .local_gateway import LocalExportGateway
    with _generation_lock, runtime_paths.use(inputs):
        old_cache = export_packaging._ASSET_CACHE
        old_gateway = workflows._data_gateway
        old_od, old_dp = od._CACHE, dp._CACHE
        od._CACHE = {"expires_at": 0.0, "data": None}
        dp._CACHE = {"expires_at": 0.0, "categories": None, "features": {}}
        export_packaging._ASSET_CACHE = {"offers": {}, "agent_photos": {}}
        workflows.configure_export_gateway(LocalExportGateway())
        try:
            yield
        finally:
            export_packaging._ASSET_CACHE = old_cache
            workflows._data_gateway = old_gateway
            od._CACHE, dp._CACHE = old_od, old_dp


def generate_domestic(inputs: LocalInputs, portal: str, offer_id: int, action: str = "add"):
    from .backend_service import execute_portal_action
    with _environment(inputs):
        return execute_portal_action(portal, offer_id, action, upload=False)


def generate_foreign(inputs: LocalInputs, portal: str, offer_id: int):
    from . import foreign_offers_export as engine
    methods = {"domiporta": engine.export_foreign_offer_to_domiporta,
               "tabelaofert": engine.export_foreign_offer_to_tabelaofert}
    if portal not in methods:
        raise ValueError("Foreign export supports domiporta or tabelaofert")
    with _environment(inputs):
        return methods[portal](offer_id, upload=False)


def generate_cyprus(inputs: LocalInputs, development_id: int):
    from .foreign_offers_export import build_cyprus_development_tabelaofert_package
    with _environment(inputs):
        return build_cyprus_development_tabelaofert_package(development_id)


def generate_withdrawal(inputs: LocalInputs, portal: str, offer_id: int):
    from .foreign_offers_export import build_foreign_withdrawal_package
    with _environment(inputs):
        return build_foreign_withdrawal_package(offer_id, portal)
