"""Extract still frames from interview video for face / liveness analysis."""

from __future__ import annotations

import base64
import logging
import shutil
import tempfile
from dataclasses import dataclass, field
from pathlib import Path

import cv2
import numpy as np

from app.config import get_settings

logger = logging.getLogger(__name__)


class VideoFrameError(Exception):
    def __init__(self, message: str, *, code: str = "video_error") -> None:
        self.code = code
        super().__init__(message)


@dataclass
class ExtractedFrames:
    frames_bgr: list[np.ndarray]
    frame_indices: list[int]
    timestamps_ms: list[int | None]
    duration_seconds: float | None
    source_fps: float | None
    sample_fps: float
    warnings: list[str] = field(default_factory=list)
    work_dir: Path | None = None

    def cleanup(self) -> None:
        if self.work_dir is not None:
            shutil.rmtree(self.work_dir, ignore_errors=True)


def frame_timestamp_ms(frame_index: int, source_fps: float | None) -> int | None:
    """Convert source frame index to milliseconds; None if FPS unknown."""
    if source_fps is None or source_fps <= 0:
        return None
    return int(round(frame_index / source_fps * 1000.0))


def compute_sample_indices(
    *,
    frame_count: int,
    source_fps: float | None,
    sample_fps: float,
    max_frames: int,
) -> list[int]:
    """Choose up to ``max_frames`` indices evenly spanning the full clip.

    ``sample_fps`` sets the desired sampling density over the whole duration.
    When that would exceed ``max_frames``, indices are still spread across
    ``[0, frame_count)`` instead of truncating to a prefix of the video.
    """
    if frame_count <= 0 or max_frames <= 0:
        return []
    if frame_count == 1:
        return [0]

    if source_fps is not None and source_fps > 0:
        duration = frame_count / source_fps
        n_from_rate = max(1, int(round(duration * sample_fps)))
    else:
        step = max(1, int(round(1.0 / sample_fps))) if sample_fps >= 1 else 1
        n_from_rate = max(1, (frame_count + step - 1) // step)

    n = min(int(max_frames), n_from_rate, frame_count)
    if n <= 1:
        return [0]
    if n >= frame_count:
        return list(range(frame_count))

    raw = np.linspace(0, frame_count - 1, num=n)
    indices: list[int] = []
    seen: set[int] = set()
    for value in raw:
        idx = int(round(float(value)))
        idx = max(0, min(frame_count - 1, idx))
        if idx not in seen:
            seen.add(idx)
            indices.append(idx)

    # Rare linspace collisions on tiny clips — top up from unused indices
    if len(indices) < n:
        for idx in range(frame_count):
            if idx not in seen:
                seen.add(idx)
                indices.append(idx)
                if len(indices) >= n:
                    break
        indices.sort()
    return indices


def _evenly_subsample(
    items: list[tuple[int, np.ndarray]], max_frames: int
) -> list[tuple[int, np.ndarray]]:
    """Keep up to max_frames items evenly spaced across the candidate list."""
    if len(items) <= max_frames or max_frames <= 0:
        return items
    raw = np.linspace(0, len(items) - 1, num=max_frames)
    pick: list[int] = []
    seen: set[int] = set()
    for value in raw:
        idx = int(round(float(value)))
        idx = max(0, min(len(items) - 1, idx))
        if idx not in seen:
            seen.add(idx)
            pick.append(idx)
    return [items[i] for i in pick]


def decode_video_base64(data_b64: str, *, max_bytes: int) -> bytes:
    raw = (data_b64 or "").strip()
    if not raw:
        raise VideoFrameError("Empty video payload", code="invalid_video")
    if "," in raw and raw.lower().startswith("data:"):
        raw = raw.split(",", 1)[1]
    # Reject oversized payloads before allocating decoded buffer
    # base64 expands ~4/3; estimate decoded size from encoded length
    encoded_len = len(raw)
    approx_decoded = (encoded_len * 3) // 4
    if approx_decoded > max_bytes:
        raise VideoFrameError(
            f"Video exceeds max size ({max_bytes} bytes)",
            code="video_too_large",
        )
    try:
        data = base64.b64decode(raw, validate=False)
    except Exception as exc:  # noqa: BLE001
        raise VideoFrameError("Invalid base64 video encoding", code="invalid_video") from exc
    if len(data) < 64:
        raise VideoFrameError("Video payload too small", code="invalid_video")
    if len(data) > max_bytes:
        raise VideoFrameError(
            f"Video exceeds max size ({max_bytes} bytes)",
            code="video_too_large",
        )
    return data


def extract_frames_from_bytes(
    video_bytes: bytes,
    *,
    sample_fps: float,
    max_frames: int | None = None,
    filename_hint: str = "clip.mp4",
) -> ExtractedFrames:
    """Write bytes to a temp file and sample frames with OpenCV.

    Samples are distributed across the full video duration (not a prefix).
    When source FPS and frame count are known, seeks to target indices.
    Falls back to sequential decode, then evenly subsamples to max_frames.
    """
    settings = get_settings()
    max_frames = int(max_frames or settings.video_max_frames)
    sample_fps = float(sample_fps)
    if sample_fps <= 0:
        raise VideoFrameError("sample_fps must be > 0", code="invalid_sample_fps")

    from app.services.video.url_safety import looks_like_video_bytes

    if not looks_like_video_bytes(video_bytes):
        # Soft check — OpenCV may still open some odd containers; warn via failure later
        logger.info("Video magic-byte sniff did not match common containers")

    work = Path(tempfile.mkdtemp(prefix="tj_video_"))
    suffix = Path(filename_hint).suffix or ".mp4"
    path = work / f"input{suffix}"
    path.write_bytes(video_bytes)

    cap: cv2.VideoCapture | None = None
    warnings: list[str] = []
    try:
        cap = cv2.VideoCapture(str(path))
        if not cap.isOpened():
            alt = work / "input.avi"
            alt.write_bytes(video_bytes)
            cap.release()
            cap = cv2.VideoCapture(str(alt))
        if not cap.isOpened():
            raise VideoFrameError(
                "Could not open video — unsupported codec or corrupt file",
                code="unsupported_video",
            )

        source_fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) or None
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
        duration = None
        if source_fps and source_fps > 0 and frame_count > 0:
            duration = frame_count / source_fps
            max_dur = float(settings.video_max_duration_seconds)
            if duration > max_dur:
                raise VideoFrameError(
                    f"Video duration {duration:.1f}s exceeds max {max_dur}s",
                    code="video_too_long",
                )

        if source_fps and source_fps > 0:
            step = max(1, int(round(source_fps / sample_fps)))
        else:
            step = max(1, int(round(1.0 / sample_fps))) if sample_fps >= 1 else 1
            warnings.append("Source FPS unknown — using index step heuristic")

        frames: list[np.ndarray] = []
        indices: list[int] = []
        seek_ok = False

        use_seek = bool(source_fps and source_fps > 0 and frame_count > 0)
        if use_seek:
            targets = compute_sample_indices(
                frame_count=frame_count,
                source_fps=source_fps,
                sample_fps=sample_fps,
                max_frames=max_frames,
            )
            for target in targets:
                cap.set(cv2.CAP_PROP_POS_FRAMES, float(target))
                ok, frame = cap.read()
                if not ok or frame is None:
                    warnings.append(
                        "Frame seek unreliable — falling back to sequential decode"
                    )
                    frames.clear()
                    indices.clear()
                    break
                frames.append(frame.copy())
                indices.append(int(target))
            else:
                seek_ok = bool(frames)

        if not seek_ok:
            cap.set(cv2.CAP_PROP_POS_FRAMES, 0.0)
            candidates: list[tuple[int, np.ndarray]] = []
            idx = 0
            while True:
                ok, frame = cap.read()
                if not ok or frame is None:
                    break
                if idx % step == 0:
                    candidates.append((idx, frame.copy()))
                idx += 1

            if frame_count <= 0 and idx > 0:
                frame_count = idx
                if source_fps and source_fps > 0:
                    duration = frame_count / source_fps

            # Prefer full-span subsample of rate-based candidates; if we somehow
            # collected fewer than desired because step was coarse, keep all.
            selected = _evenly_subsample(candidates, max_frames)
            frames = [f for _, f in selected]
            indices = [i for i, _ in selected]

        if not frames:
            raise VideoFrameError("No frames extracted from video", code="no_frames")

        if len(frames) < int(settings.face_min_live_frames):
            warnings.append(
                f"Extracted only {len(frames)} frame(s); "
                f"prefer ≥{settings.face_min_live_frames} for robust liveness"
            )

        if (
            duration is not None
            and source_fps
            and source_fps > 0
            and indices
            and len(indices) >= 2
        ):
            span_ms = frame_timestamp_ms(indices[-1], source_fps) or 0
            coverage = span_ms / max(1.0, duration * 1000.0)
            if coverage < 0.5:
                warnings.append(
                    f"Sample span covers only {coverage * 100:.0f}% of duration — "
                    "check codec frame indexing"
                )

        timestamps = [frame_timestamp_ms(i, source_fps) for i in indices]
        if source_fps is None or source_fps <= 0:
            warnings.append(
                "Source FPS unknown — frame timestamps unavailable (indices only)"
            )

        return ExtractedFrames(
            frames_bgr=frames,
            frame_indices=indices,
            timestamps_ms=timestamps,
            duration_seconds=duration,
            source_fps=source_fps,
            sample_fps=sample_fps,
            warnings=warnings,
            work_dir=work,
        )
    except VideoFrameError:
        shutil.rmtree(work, ignore_errors=True)
        raise
    except Exception:
        shutil.rmtree(work, ignore_errors=True)
        raise
    finally:
        if cap is not None:
            cap.release()
