"""Shared SDK 5.0.0 ingestion settings helpers."""

from __future__ import annotations

import json
import logging
from dataclasses import dataclass, field

from worai.errors import UsageError

LOGGER = logging.getLogger("worai.ingest")

INGEST_SOURCES = {"auto", "urls", "sitemap", "sheets", "local"}
INGEST_LOADERS = {
    "auto",
    "simple",
    "proxy",
    "playwright",
    "premium_scraper",
    "web_scrape_api",
    "passthrough",
}
LEGACY_SOURCE_ALIASES = {
    "debug-cloud": "local",
    "local": "local",
}
LEGACY_LOADER_MAP = {
    "default": "web_scrape_api",
    "proxy": "proxy",
    "premium_scraper": "premium_scraper",
    "web_scrape_api": "web_scrape_api",
    "playwright": "playwright",
    "simple": "simple",
    "passthrough": "passthrough",
}
DEFAULT_INGEST_SOURCE = "auto"
DEFAULT_INGEST_LOADER = "web_scrape_api"
DEFAULT_PASSTHROUGH_WHEN_HTML = True


def _normalize_source(value: str | None) -> str | None:
    if value is None:
        return None
    item = value.strip().lower()
    if not item:
        return None
    return LEGACY_SOURCE_ALIASES.get(item, item)


def _normalize_loader(value: str | None) -> str | None:
    if value is None:
        return None
    item = value.strip().lower()
    if not item:
        return None
    return LEGACY_LOADER_MAP.get(item, item)


def _validate_source(value: str) -> str:
    if value not in INGEST_SOURCES:
        raise UsageError(
            f"Invalid ingest source '{value}'. Allowed: {', '.join(sorted(INGEST_SOURCES))}."
        )
    return value


def _validate_loader(value: str) -> str:
    if value not in INGEST_LOADERS:
        raise UsageError(
            f"Invalid ingest loader '{value}'. Allowed: {', '.join(sorted(INGEST_LOADERS))}."
        )
    return value


@dataclass
class IngestSettings:
    source: str
    loader: str
    passthrough_when_html: bool
    warnings: list[dict[str, object]] = field(default_factory=list)


def _emit_conflict_warning(
    *,
    context: str,
    new_key: str,
    new_value: str,
    legacy_key: str,
    legacy_value: str,
) -> dict[str, object]:
    payload = {
        "event": "ingest_config_conflict",
        "context": context,
        "new_key": new_key,
        "new_value": new_value,
        "legacy_key": legacy_key,
        "legacy_value": legacy_value,
        "winner": "new",
    }
    LOGGER.warning(json.dumps(payload, sort_keys=True, ensure_ascii=True))
    return payload


def resolve_ingest_settings(
    *,
    context: str,
    new_source: str | None = None,
    new_loader: str | None = None,
    new_passthrough_when_html: bool | None = None,
    legacy_source: str | None = None,
    legacy_loader: str | None = None,
    default_source: str = DEFAULT_INGEST_SOURCE,
    default_loader: str = DEFAULT_INGEST_LOADER,
) -> IngestSettings:
    warnings: list[dict[str, object]] = []

    normalized_new_source = _normalize_source(new_source)
    normalized_legacy_source = _normalize_source(legacy_source)
    normalized_new_loader = _normalize_loader(new_loader)
    normalized_legacy_loader = _normalize_loader(legacy_loader)

    source = normalized_new_source or normalized_legacy_source or default_source
    loader = normalized_new_loader or normalized_legacy_loader or default_loader

    if (
        normalized_new_source
        and normalized_legacy_source
        and normalized_new_source != normalized_legacy_source
    ):
        warnings.append(
            _emit_conflict_warning(
                context=context,
                new_key="ingest.source",
                new_value=normalized_new_source,
                legacy_key="source_type",
                legacy_value=normalized_legacy_source,
            )
        )

    if (
        normalized_new_loader
        and normalized_legacy_loader
        and normalized_new_loader != normalized_legacy_loader
    ):
        warnings.append(
            _emit_conflict_warning(
                context=context,
                new_key="ingest.loader",
                new_value=normalized_new_loader,
                legacy_key="web_page_import_mode",
                legacy_value=normalized_legacy_loader,
            )
        )

    if new_passthrough_when_html is None:
        passthrough_when_html = DEFAULT_PASSTHROUGH_WHEN_HTML
    else:
        passthrough_when_html = bool(new_passthrough_when_html)

    return IngestSettings(
        source=_validate_source(source),
        loader=_validate_loader(loader),
        passthrough_when_html=passthrough_when_html,
        warnings=warnings,
    )
