import logging
import time

from .portals import (
    execute_domiporta_workflow,
    execute_gruntguru_workflow,
    execute_no_workflow,
    execute_otodom_workflow,
    execute_tabelaofert_workflow,
    fetch_export_context,
)
_perf_logger = logging.getLogger("portal_perf")


def _execute_portal_action_with_context(portal_key, mode, upload, *, offer_id, context):
    normalized_portal = str(portal_key).strip().lower()
    normalized_mode = str(mode).strip().lower()
    if normalized_mode not in {"add", "delete"}:
        raise ValueError("mode must be one of: add, delete")

    offer_data = context.offer_data
    location_data = context.location_data
    agent_data = context.agent_data
    description = context.description
    num_photos = context.num_photos

    if normalized_portal == "no":
        return execute_no_workflow(
            offer_id,
            offer_data,
            location_data,
            agent_data,
            description,
            num_photos,
            xml_option="insert" if normalized_mode == "add" else "delete",
            package_action="Dodaj" if normalized_mode == "add" else "Usuń",
            package_agent_id=offer_data.agent_id,
            upload=upload,
        )

    if normalized_portal == "otodom":
        return execute_otodom_workflow(
            offer_id,
            offer_data,
            location_data,
            agent_data,
            description,
            num_photos,
            xml_option="insert" if normalized_mode == "add" else "delete",
            package_action="Dodaj" if normalized_mode == "add" else "Usuń",
            street_source="offer" if normalized_mode == "add" else "location",
            package_agent_id=offer_data.agent_id,
            upload=upload,
        )

    if normalized_portal == "domiporta":
        return execute_domiporta_workflow(
            offer_id,
            offer_data,
            location_data,
            agent_data,
            description,
            num_photos,
            xml_option="insert" if normalized_mode == "add" else "delete",
            package_action="Dodaj" if normalized_mode == "add" else "Usuń",
            package_agent_id=offer_data.agent_id,
            upload=upload,
        )

    if normalized_portal == "tabelaofert":
        return execute_tabelaofert_workflow(
            offer_id,
            offer_data,
            location_data,
            agent_data,
            description,
            num_photos,
            xml_option="insert" if normalized_mode == "add" else "delete",
            package_action="Dodaj" if normalized_mode == "add" else "Usuń",
            package_agent_id=offer_data.agent_id,
            upload=upload,
        )

    if normalized_portal == "gruntguru":
        return execute_gruntguru_workflow(
            offer_id,
            offer_data,
            location_data,
            agent_data,
            description,
            num_photos,
            xml_option="insert" if normalized_mode == "add" else "delete",
            package_action="Dodaj" if normalized_mode == "add" else "Usuń",
            package_agent_id=offer_data.agent_id,
            upload=upload,
        )

    raise ValueError("portal_key must be one of: no, otodom, domiporta, tabelaofert, gruntguru")


def execute_portal_action(portal_key, offer_id, mode, upload):
    t0 = time.perf_counter()
    normalized_portal = str(portal_key).strip().lower()
    context = fetch_export_context(offer_id)
    result = _execute_portal_action_with_context(
        portal_key=normalized_portal,
        mode=mode,
        upload=upload,
        offer_id=offer_id,
        context=context,
    )
    _perf_logger.info(
        "offer=%s portal=%s mode=%s stage=execute_portal_action total_ms=%.2f",
        offer_id,
        normalized_portal,
        mode,
        (time.perf_counter() - t0) * 1000,
    )
    return result


def execute_portal_actions(portal_keys, offer_id, mode, upload):
    t0 = time.perf_counter()
    context = fetch_export_context(offer_id)
    results = {}
    errors = {}

    for portal_key in portal_keys:
        normalized_portal = str(portal_key).strip().lower()
        try:
            results[normalized_portal] = _execute_portal_action_with_context(
                portal_key=normalized_portal,
                mode=mode,
                upload=upload,
                offer_id=offer_id,
                context=context,
            )
        except Exception as exc:
            errors[normalized_portal] = str(exc)

    _perf_logger.info(
        "offer=%s portals=%s mode=%s stage=execute_portal_actions total_ms=%.2f ok=%s errors=%s",
        offer_id,
        ",".join(str(p) for p in portal_keys),
        mode,
        (time.perf_counter() - t0) * 1000,
        len(results),
        len(errors),
    )
    return results, errors
