"""Face enrollment + interview verification (ArcFace vs enrolled reference + liveness)."""

from __future__ import annotations

import asyncio
import base64
import logging
from datetime import timedelta
from typing import Any

import httpx
import numpy as np

from app.config import get_settings
from app.schemas.common import JobStatus
from app.schemas.face_verification import (
    FaceEnrollRequest,
    FaceEnrollResponse,
    FaceFrameResult,
    FaceManualReviewRequest,
    FaceManualReviewResponse,
    FaceVerificationRequest,
    FaceVerificationResponse,
    IdentityMatchResult,
    LivenessResult,
)
from app.services.face.audit_store import (
    FaceAuditRecord,
    face_audit_store,
    new_audit_id,
    _iso,
    _utc_now,
)
from app.services.face.deps import FaceStackStatus, require_face_stack
from app.services.face.engine import FaceEngineResult, get_face_engine
from app.services.face.enrollment_store import face_enrollment_store
from app.services.face.image_ops import FaceImageError, decode_base64_image
from app.services.face.video_frames import VideoFrameError, extract_frames_from_bytes

logger = logging.getLogger(__name__)


class FaceVerificationService:
    async def enroll(self, payload: FaceEnrollRequest) -> FaceEnrollResponse:
        """Registration: live scan → liveness → encrypted face reference."""
        settings = get_settings()
        gate_key = f"enroll:{payload.user_id}"
        attempt = face_audit_store.attempt_count(gate_key) + 1
        max_attempts = int(settings.face_max_attempts)
        attempts_remaining = max(0, max_attempts - attempt)
        retry_allowed = attempt < max_attempts
        warnings: list[str] = []

        if attempt > max_attempts:
            return self._enroll_fail(
                payload,
                message="Maximum face enrollment attempts exceeded",
                error_code="max_attempts_exceeded",
                attempt=attempt,
                attempts_remaining=0,
                retry_allowed=False,
            )
        if not payload.consent_given:
            return self._enroll_fail(
                payload,
                message="Explicit consent required (consent_given=true)",
                error_code="consent_required",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        deps: FaceStackStatus | None = None
        try:
            deps = await asyncio.to_thread(require_face_stack)
        except RuntimeError as exc:
            return self._enroll_fail(
                payload,
                message=str(exc),
                error_code="deps_unavailable",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )
        if deps and deps.warnings:
            warnings.extend(deps.warnings)

        try:
            live_bgr, live_sha, frame_warnings = await self._load_live_frames(payload)
            warnings.extend(frame_warnings)
        except (FaceImageError, VideoFrameError) as exc:
            return self._enroll_fail(
                payload,
                message=str(exc),
                error_code=getattr(exc, "code", "media_error"),
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        if len(live_bgr) < int(settings.face_min_live_frames):
            return self._enroll_fail(
                payload,
                message=(
                    f"Need at least {settings.face_min_live_frames} live frame(s); "
                    f"got {len(live_bgr)}. Live camera capture required."
                ),
                error_code="insufficient_frames",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        engine = get_face_engine()
        try:
            # Liveness-only pass (no enrolled reference yet)
            result: FaceEngineResult = await asyncio.to_thread(
                engine.analyze,
                registered_bgr=None,
                live_frames_bgr=live_bgr,
            )
        except Exception as exc:  # noqa: BLE001
            logger.exception("Face enroll engine failed")
            return self._enroll_fail(
                payload,
                message=f"Face analysis failed: {type(exc).__name__}",
                error_code="engine_error",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        warnings.extend(result.warnings)
        liveness = self._liveness_from_result(result)
        if not result.liveness_passed:
            audit_id = self._append_audit(
                interview_id=gate_key,
                candidate_id=payload.user_id,
                verified=False,
                identity_matched=False,
                liveness_passed=False,
                result=result,
                attempt=attempt,
                frame_count=len(live_bgr),
                registered_sha=None,
                live_sha=live_sha,
                error_code=liveness.error_code or "liveness_failed",
                warnings=warnings,
            )
            return FaceEnrollResponse(
                correlation_id=payload.correlation_id,
                user_id=payload.user_id,
                company_id=payload.company_id,
                enrolled=False,
                liveness_passed=False,
                liveness=liveness,
                consent_recorded=True,
                consent_id=payload.consent_id,
                reference_stored=False,
                status=JobStatus.FAILED,
                stub=False,
                message="Liveness check failed — retry with a live camera scan",
                audit_id=audit_id,
                frame_count=len(live_bgr),
                attempt=attempt,
                attempts_remaining=max(0, max_attempts - attempt),
                retry_allowed=attempt < max_attempts,
                error_code=liveness.error_code or "liveness_failed",
                warnings=warnings,
                model=result.model,
                detector=result.detector,
                deps_ok=True if deps is None else deps.ok,
            )

        # Persist best live frame as encrypted enrollment reference (not returned raw)
        ref_idx = 0
        for i, fr in enumerate(result.frame_results):
            if fr.faces_detected and fr.is_real:
                ref_idx = i
                break
        ref_bgr = live_bgr[min(ref_idx, len(live_bgr) - 1)]
        ok, buf = self._encode_png(ref_bgr)
        if not ok or not buf:
            return self._enroll_fail(
                payload,
                message="Could not encode enrollment reference frame",
                error_code="enrollment_encode_failed",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        try:
            enrollment = face_enrollment_store.save_enrollment(
                user_id=payload.user_id,
                image_bytes=buf,
                company_id=payload.company_id,
                consent_id=payload.consent_id,
                meta={"frame_count": len(live_bgr), "source": "live_enroll"},
            )
        except Exception as exc:  # noqa: BLE001
            logger.exception("Face enrollment store failed")
            return self._enroll_fail(
                payload,
                message=f"Could not store face reference: {type(exc).__name__}",
                error_code="enrollment_store_failed",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        now = _utc_now()
        audit_id = self._append_audit(
            interview_id=gate_key,
            candidate_id=payload.user_id,
            verified=True,
            identity_matched=True,
            liveness_passed=True,
            result=result,
            attempt=attempt,
            frame_count=len(live_bgr),
            registered_sha=enrollment.image_sha256,
            live_sha=live_sha,
            error_code=None,
            warnings=warnings + ["enrollment_created"],
            expires_at=None,
        )
        return FaceEnrollResponse(
            correlation_id=payload.correlation_id,
            user_id=payload.user_id,
            company_id=payload.company_id,
            enrollment_id=enrollment.enrollment_id,
            enrolled=True,
            liveness_passed=True,
            liveness=liveness,
            consent_recorded=True,
            consent_id=payload.consent_id,
            reference_stored=True,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message="Live face enrolled — reference stored encrypted (not returned)",
            audit_id=audit_id,
            enrolled_at=_iso(now),
            frame_count=len(live_bgr),
            attempt=attempt,
            attempts_remaining=max(0, max_attempts - attempt),
            retry_allowed=False,
            warnings=warnings,
            model=result.model,
            detector=result.detector,
            deps_ok=True if deps is None else deps.ok,
        )

    async def verify(self, payload: FaceVerificationRequest) -> FaceVerificationResponse:
        """Interview: live scan → liveness → match enrolled reference."""
        settings = get_settings()
        interview_id = (payload.interview_id or "").strip() or f"int-face-{payload.user_id}"
        payload = payload.model_copy(update={"interview_id": interview_id})

        max_attempts = int(settings.face_max_attempts)
        attempt = face_audit_store.attempt_count(interview_id) + 1
        attempts_remaining = max(0, max_attempts - attempt)
        retry_allowed = attempt < max_attempts
        warnings: list[str] = []

        if attempt > max_attempts:
            return self._verify_fail(
                payload,
                message="Maximum face verification attempts exceeded",
                error_code="max_attempts_exceeded",
                attempt=attempt,
                attempts_remaining=0,
                retry_allowed=False,
            )
        if not payload.consent_given:
            return self._verify_fail(
                payload,
                message="Explicit candidate consent required (consent_given=true)",
                error_code="consent_required",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
            )

        enrollment = face_enrollment_store.get_active(payload.user_id)
        if enrollment is None:
            return self._verify_fail(
                payload,
                message=(
                    "No active face enrollment for this user. "
                    "Complete POST /face-verification/enroll during registration first."
                ),
                error_code="enrollment_required",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=False,
            )

        raw = face_enrollment_store.load_image_bytes(payload.user_id)
        if not raw:
            return self._verify_fail(
                payload,
                message="Could not load enrolled face reference",
                error_code="enrollment_load_failed",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                enrollment_id=enrollment.enrollment_id,
            )

        deps: FaceStackStatus | None = None
        try:
            deps = await asyncio.to_thread(require_face_stack)
        except RuntimeError as exc:
            return self._verify_fail(
                payload,
                message=str(exc),
                error_code="deps_unavailable",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                enrollment_id=enrollment.enrollment_id,
            )
        if deps and deps.warnings:
            warnings.extend(deps.warnings)

        warnings.append("Identity match reference: enrolled live face template")

        try:
            registered = decode_base64_image(
                base64.b64encode(raw).decode("ascii"),
                max_bytes=int(settings.face_max_image_bytes),
            )
            live_bgr, live_sha, frame_warnings = await self._load_live_frames(payload)
            warnings.extend(frame_warnings)
        except (FaceImageError, VideoFrameError) as exc:
            return self._verify_fail(
                payload,
                message=str(exc),
                error_code=getattr(exc, "code", "media_error"),
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                enrollment_id=enrollment.enrollment_id,
            )

        if len(live_bgr) < int(settings.face_min_live_frames):
            return self._verify_fail(
                payload,
                message=(
                    f"Need at least {settings.face_min_live_frames} live frame(s); "
                    f"got {len(live_bgr)}"
                ),
                error_code="insufficient_frames",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                enrollment_id=enrollment.enrollment_id,
            )

        engine = get_face_engine()
        try:
            result = await asyncio.to_thread(
                engine.analyze,
                registered_bgr=registered.bgr,
                live_frames_bgr=live_bgr,
            )
        except Exception as exc:  # noqa: BLE001
            logger.exception("Face verify engine failed")
            return self._verify_fail(
                payload,
                message=f"Face analysis failed: {type(exc).__name__}",
                error_code="engine_error",
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                enrollment_id=enrollment.enrollment_id,
            )

        warnings.extend(result.warnings)
        identity = IdentityMatchResult(
            matched=result.identity_matched,
            match_score=result.match_score,
            distance=result.distance,
            threshold=result.threshold,
            model=result.model,
            reference_source="enrollment",
            error_code=(
                None
                if result.identity_matched
                else (
                    result.error_code
                    if result.error_code
                    and result.error_code
                    not in {"liveness_failed", "liveness_and_identity_failed"}
                    else "identity_mismatch"
                    if result.identity_matched is False
                    else None
                )
            ),
        )
        liveness = self._liveness_from_result(result)
        verified = bool(
            result.identity_matched is True and result.liveness_passed is True
        )
        error_code = None if verified else (result.error_code or "checks_failed")

        ttl = float(settings.face_verification_ttl_seconds)
        now = _utc_now()
        expires = now + timedelta(seconds=ttl) if verified else None
        audit_id = self._append_audit(
            interview_id=interview_id,
            candidate_id=payload.candidate_id or payload.user_id,
            verified=verified,
            identity_matched=bool(result.identity_matched),
            liveness_passed=bool(result.liveness_passed),
            result=result,
            attempt=attempt,
            frame_count=len(live_bgr),
            registered_sha=enrollment.image_sha256,
            live_sha=live_sha,
            error_code=error_code,
            warnings=warnings,
            expires_at=_iso(expires) if expires else None,
        )

        return FaceVerificationResponse(
            correlation_id=payload.correlation_id,
            interview_id=interview_id,
            user_id=payload.user_id,
            candidate_id=payload.candidate_id,
            status=JobStatus.SUCCEEDED if verified else JobStatus.FAILED,
            stub=False,
            message=(
                "Face matched enrollment and liveness passed — interview may proceed"
                if verified
                else f"Face verification failed: {error_code or 'checks_failed'}"
            ),
            verified=verified,
            identity=identity,
            liveness=liveness,
            identity_matched=result.identity_matched,
            liveness_passed=result.liveness_passed,
            match_score=result.match_score,
            distance=result.distance,
            threshold=result.threshold,
            liveness_score=result.liveness_score,
            reference_source="enrollment",
            enrollment_id=enrollment.enrollment_id,
            consent_recorded=True,
            consent_id=payload.consent_id,
            model=result.model,
            detector=result.detector,
            deps_ok=True if deps is None else deps.ok,
            face_count=result.face_count,
            frame_count=len(live_bgr),
            frame_results=[
                FaceFrameResult(
                    face_count=fr.face_count,
                    is_real=fr.is_real,
                    antispoof_score=fr.antispoof_score,
                    quality_warnings=fr.quality_warnings,
                    error=fr.error,
                    faces_detected=fr.faces_detected,
                )
                for fr in result.frame_results
            ],
            attempt=attempt,
            attempts_remaining=max(0, max_attempts - attempt),
            retry_allowed=(not verified) and (attempt < max_attempts),
            audit_id=audit_id,
            verified_at=_iso(now) if verified else None,
            expires_at=_iso(expires) if expires else None,
            error_code=error_code,
            warnings=warnings,
            manual_review_available=(not verified) and attempt >= 1,
        )

    async def manual_review(
        self, payload: FaceManualReviewRequest
    ) -> FaceManualReviewResponse:
        """False-rejection fallback — reviewer approves interview access."""
        settings = get_settings()
        enrollment = face_enrollment_store.get_active(payload.user_id)
        if enrollment is None:
            return FaceManualReviewResponse(
                correlation_id=payload.correlation_id,
                user_id=payload.user_id,
                interview_id=payload.interview_id,
                approved=False,
                status=JobStatus.FAILED,
                stub=False,
                message="No enrollment for user — cannot approve without registration face",
                reviewer_id=payload.reviewer_id,
            )

        ttl = float(settings.face_verification_ttl_seconds)
        now = _utc_now()
        expires = now + timedelta(seconds=ttl)
        audit_id = new_audit_id()
        face_audit_store.append(
            FaceAuditRecord(
                audit_id=audit_id,
                interview_id=payload.interview_id,
                candidate_id=payload.candidate_id or payload.user_id,
                status="passed",
                verified=True,
                identity_matched=True,
                liveness_passed=True,
                match_score=None,
                distance=None,
                threshold=None,
                liveness_score=None,
                model="manual_review",
                detector="human",
                attempt=face_audit_store.attempt_count(payload.interview_id) + 1,
                face_count=None,
                frame_count=0,
                registered_image_sha256=enrollment.image_sha256,
                live_image_sha256s=[],
                error_code=None,
                warnings=[
                    "manual_review_override",
                    f"reviewer={payload.reviewer_id}",
                    f"reason={payload.reason[:200]}",
                ],
                created_at=_iso(now),
                expires_at=_iso(expires),
            )
        )
        return FaceManualReviewResponse(
            correlation_id=payload.correlation_id,
            user_id=payload.user_id,
            interview_id=payload.interview_id,
            approved=True,
            audit_id=audit_id,
            verified_at=_iso(now),
            expires_at=_iso(expires),
            reviewer_id=payload.reviewer_id,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message="Manual review approved — interview may proceed within TTL",
        )

    async def _load_live_frames(
        self, payload: Any
    ) -> tuple[list[np.ndarray], list[str], list[str]]:
        settings = get_settings()
        warnings: list[str] = []
        extracted = None
        live_list = list(getattr(payload, "live_frames_base64", None) or [])
        live_image = getattr(payload, "live_image_base64", None)
        if live_image:
            live_list.append(live_image)
        source_url = getattr(payload, "source_url", None)
        video_b64 = getattr(payload, "video_base64", None)
        video_fps = float(getattr(payload, "video_sample_fps", 1.0) or 1.0)

        try:
            max_bytes = int(settings.face_max_image_bytes)
            live_bgr: list[np.ndarray] = []
            live_sha: list[str] = []

            if source_url and not live_list and not video_b64:
                live_bytes = await self._fetch_url(source_url)
                live_list.append(base64.b64encode(live_bytes).decode("ascii"))

            if live_list:
                live_decoded = [
                    decode_base64_image(b64, max_bytes=max_bytes) for b64 in live_list
                ]
                live_bgr.extend(d.bgr for d in live_decoded)
                live_sha.extend(d.content_sha256 for d in live_decoded)

            if video_b64:
                from app.services.face.video_frames import decode_video_base64

                vid_bytes = decode_video_base64(
                    video_b64,
                    max_bytes=int(settings.video_max_upload_bytes),
                )
                extracted = await asyncio.to_thread(
                    extract_frames_from_bytes,
                    vid_bytes,
                    sample_fps=video_fps,
                    max_frames=int(settings.face_max_live_frames),
                )
                warnings.extend(extracted.warnings)
                live_bgr.extend(extracted.frames_bgr)

            max_frames = int(settings.face_max_live_frames)
            if len(live_bgr) > max_frames:
                live_bgr = live_bgr[:max_frames]
            return live_bgr, live_sha, warnings
        finally:
            if extracted is not None:
                extracted.cleanup()

    def _liveness_from_result(self, result: FaceEngineResult) -> LivenessResult:
        settings = get_settings()
        liveness_error = None
        if not result.liveness_passed:
            liveness_error = (
                result.error_code
                if result.error_code
                in {
                    "insufficient_liveness_data",
                    "insufficient_face_presence",
                    "liveness_failed",
                    "no_live_frames",
                }
                else "liveness_failed"
            )
        return LivenessResult(
            passed=result.liveness_passed,
            score=result.liveness_score,
            frame_pass_ratio=result.liveness_frame_pass_ratio,
            threshold=float(settings.face_liveness_score_threshold),
            frame_pass_ratio_threshold=float(settings.face_liveness_frame_pass_ratio),
            error_code=liveness_error,
        )

    def _append_audit(
        self,
        *,
        interview_id: str,
        candidate_id: str | None,
        verified: bool,
        identity_matched: bool,
        liveness_passed: bool,
        result: FaceEngineResult,
        attempt: int,
        frame_count: int,
        registered_sha: str | None,
        live_sha: list[str],
        error_code: str | None,
        warnings: list[str],
        expires_at: str | None = None,
    ) -> str:
        audit_id = new_audit_id()
        face_audit_store.append(
            FaceAuditRecord(
                audit_id=audit_id,
                interview_id=interview_id,
                candidate_id=candidate_id,
                status="passed" if verified else "failed",
                verified=verified,
                identity_matched=identity_matched,
                liveness_passed=liveness_passed,
                match_score=result.match_score,
                distance=result.distance,
                threshold=result.threshold,
                liveness_score=result.liveness_score,
                model=result.model,
                detector=result.detector,
                attempt=attempt,
                face_count=result.face_count,
                frame_count=frame_count,
                registered_image_sha256=registered_sha,
                live_image_sha256s=live_sha,
                error_code=error_code,
                warnings=list(warnings),
                created_at=_iso(_utc_now()),
                expires_at=expires_at,
            )
        )
        return audit_id

    @staticmethod
    def _encode_png(bgr: np.ndarray) -> tuple[bool, bytes | None]:
        try:
            import cv2

            ok, buf = cv2.imencode(".png", bgr)
            if not ok:
                return False, None
            return True, buf.tobytes()
        except Exception:  # noqa: BLE001
            return False, None

    def _enroll_fail(
        self,
        payload: FaceEnrollRequest,
        *,
        message: str,
        error_code: str,
        attempt: int,
        attempts_remaining: int,
        retry_allowed: bool,
    ) -> FaceEnrollResponse:
        settings = get_settings()
        gate_key = f"enroll:{payload.user_id}"
        audit_id = new_audit_id()
        face_audit_store.append(
            FaceAuditRecord(
                audit_id=audit_id,
                interview_id=gate_key,
                candidate_id=payload.user_id,
                status="failed",
                verified=False,
                identity_matched=False,
                liveness_passed=False,
                match_score=None,
                distance=None,
                threshold=None,
                liveness_score=None,
                model=settings.face_verification_model,
                detector=settings.face_detector_backend,
                attempt=attempt,
                face_count=None,
                frame_count=len(payload.live_frames_base64 or [])
                + (1 if payload.live_image_base64 else 0),
                registered_image_sha256=None,
                error_code=error_code,
                warnings=[message],
                created_at=_iso(_utc_now()),
            )
        )
        return FaceEnrollResponse(
            correlation_id=payload.correlation_id,
            user_id=payload.user_id,
            company_id=payload.company_id,
            enrolled=False,
            reference_stored=False,
            status=JobStatus.FAILED,
            stub=False,
            message=message,
            audit_id=audit_id,
            attempt=attempt,
            attempts_remaining=attempts_remaining,
            retry_allowed=retry_allowed,
            error_code=error_code,
            warnings=[message],
            consent_recorded=bool(payload.consent_given),
            consent_id=payload.consent_id,
            model=settings.face_verification_model,
            detector=settings.face_detector_backend,
            deps_ok=error_code != "deps_unavailable",
        )

    def _verify_fail(
        self,
        payload: FaceVerificationRequest,
        *,
        message: str,
        error_code: str,
        attempt: int,
        attempts_remaining: int,
        retry_allowed: bool,
        enrollment_id: str | None = None,
    ) -> FaceVerificationResponse:
        settings = get_settings()
        audit_id = new_audit_id()
        face_audit_store.append(
            FaceAuditRecord(
                audit_id=audit_id,
                interview_id=payload.interview_id or f"int-face-{payload.user_id}",
                candidate_id=payload.candidate_id or payload.user_id,
                status="failed",
                verified=False,
                identity_matched=False,
                liveness_passed=False,
                match_score=None,
                distance=None,
                threshold=float(settings.face_match_distance_threshold)
                if settings.face_match_distance_threshold is not None
                else None,
                liveness_score=None,
                model=settings.face_verification_model,
                detector=settings.face_detector_backend,
                attempt=attempt,
                face_count=None,
                frame_count=len(payload.live_frames_base64 or [])
                + (1 if payload.live_image_base64 else 0),
                registered_image_sha256=None,
                error_code=error_code,
                warnings=[message],
                created_at=_iso(_utc_now()),
            )
        )
        return FaceVerificationResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            user_id=payload.user_id,
            candidate_id=payload.candidate_id,
            status=JobStatus.FAILED,
            stub=False,
            message=message,
            verified=False,
            identity=IdentityMatchResult(
                matched=False,
                reference_source="enrollment" if enrollment_id else "none",
                error_code=error_code,
            ),
            liveness=LivenessResult(passed=False, error_code=error_code),
            identity_matched=False,
            liveness_passed=False,
            reference_source="enrollment" if enrollment_id else "none",
            enrollment_id=enrollment_id,
            consent_recorded=bool(payload.consent_given),
            consent_id=payload.consent_id,
            attempt=attempt,
            attempts_remaining=attempts_remaining,
            retry_allowed=retry_allowed,
            audit_id=audit_id,
            error_code=error_code,
            warnings=[message],
            model=settings.face_verification_model,
            detector=settings.face_detector_backend,
            deps_ok=error_code != "deps_unavailable",
            manual_review_available=error_code
            in {"identity_mismatch", "liveness_failed", "checks_failed"},
        )

    async def _fetch_url(self, url: str) -> bytes:
        async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
            res = await client.get(url)
            res.raise_for_status()
            return res.content
