from houslyspace.utils.mark_inactive import _mark_sent_by_urls


# --- tuż nad pętlą attempt=... dodaj pomocniczą funkcję ---
def _mark_by_response_207(payload_json, page_urls: set[str]) -> int:
    """
    Zwraca liczbę oznaczonych jako wysłane.
    Traktuje 'ok' i 'duplicate' jako sukces.
    Obsługuje dwie formy: `results` (per-item) lub `errors`.
    """
    succeeded: set[str] = set()

    # 1) Prefer per-item `results`
    try:
        results = payload_json.get("results")
        if isinstance(results, list):
            for it in results:
                u = (it or {}).get("url")
                st = ((it or {}).get("status") or "").lower()
                if u and st in {"ok", "success", "created", "updated", "duplicate", "already_exists"}:
                    succeeded.add(u)
    except Exception:
        pass

    # 2) Jeśli nie było `results`, użyj `errors` i uznaj resztę za sukcesy
    if not succeeded:
        failed = set()
        try:
            for e in (payload_json or {}).get("errors", []):
                u = (e or {}).get("url")
                code = ((e or {}).get("code") or "").lower()
                msg = (((e or {}).get("message") or (e or {}).get("detail") or "") or "").lower()
                if u:
                    # Traktuj duplikaty jako sukces
                    if code in {"duplicate", "already_exists"} or "already exists" in msg:
                        succeeded.add(u)
                    else:
                        failed.add(u)
        except Exception:
            # Jeśli nie umiemy sparsować, uznaj wszystko za failed (0 success)
            failed = page_urls

        if not succeeded:
            succeeded = page_urls - failed

    if succeeded:
        _mark_sent_by_urls(succeeded)
    return len(succeeded)




def _extract_failed_urls_from_207(payload: dict) -> set[str]:
    failed = set()
    try:
        for e in (payload or {}).get("errors", []):
            u = e.get("url")
            if u:
                failed.add(u)
    except Exception:
        pass
    return failed
