"""Video intelligence — frame extract + DeepFace + evidence-linked extras."""

from __future__ import annotations

import asyncio
import base64
import logging
import time
from pathlib import Path
from urllib.parse import unquote, urlparse

import httpx

from app.config import get_settings
from app.schemas.common import JobStatus
from app.schemas.face_verification import (
    FaceFrameResult,
    IdentityMatchResult,
    LivenessResult,
)
from app.schemas.transcription import (
    TranscriptionProvider,
    TranscriptionRequest,
    TranscriptSegment,
)
from app.schemas.video_intelligence import (
    VideoIntelligenceRequest,
    VideoIntelligenceResponse,
    VideoSignal,
    VideoTranscriptBundle,
)
from app.services.face.deps import require_face_stack
from app.services.face.engine import get_face_engine
from app.services.face.image_ops import FaceImageError, decode_base64_image
from app.services.face.video_frames import (
    VideoFrameError,
    decode_video_base64,
    extract_frames_from_bytes,
)
from app.services.shared.metrics import metrics
from app.services.video.align import build_highlights
from app.services.video.audio_demux import (
    VideoAudioError,
    extract_audio_wav_from_video,
    wav_duration_ms,
)
from app.services.video.events import build_visual_events
from app.services.video.report import build_report
from app.services.video.url_safety import assert_public_http_url, looks_like_video_bytes
from app.services.voice.segment_util import synthesize_timed_segments
from app.services.voice.transcription import TranscriptionService

logger = logging.getLogger(__name__)


class VideoIntelligenceService:
    async def analyze(self, payload: VideoIntelligenceRequest) -> VideoIntelligenceResponse:
        settings = get_settings()
        warnings: list[str] = []
        limitations: list[str] = []
        t0 = time.perf_counter()
        metrics.incr("video_intelligence.requests")

        if not payload.consent_given:
            metrics.incr("video_intelligence.consent_required")
            return VideoIntelligenceResponse(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id,
                status=JobStatus.FAILED,
                stub=False,
                message="Explicit candidate consent required (consent_given=true)",
                verified=False,
                consent_recorded=False,
                identity=IdentityMatchResult(matched=None, error_code="consent_required"),
                liveness=LivenessResult(passed=False, error_code="consent_required"),
                identity_matched=None,
                liveness_passed=False,
                error_code="consent_required",
                warnings=["Consent required before biometric video analysis"],
                analysis_completeness="biometric_only",
            )

        try:
            deps = await asyncio.to_thread(require_face_stack)
            if deps.warnings:
                warnings.extend(deps.warnings)
        except RuntimeError as exc:
            return VideoIntelligenceResponse(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id,
                status=JobStatus.FAILED,
                stub=False,
                message=str(exc),
                verified=False,
                consent_recorded=True,
                deps_ok=False,
                error_code="deps_unavailable",
                warnings=[str(exc)],
                analysis_completeness="biometric_only",
            )

        extracted = None
        video_bytes: bytes | None = None
        result = None
        try:
            if payload.video_base64:
                video_bytes = decode_video_base64(
                    payload.video_base64,
                    max_bytes=int(settings.video_max_upload_bytes),
                )
            else:
                video_bytes = await self._load_source(payload.source_url or "")

            extracted = await asyncio.to_thread(
                extract_frames_from_bytes,
                video_bytes,
                sample_fps=float(payload.sample_fps),
                max_frames=payload.max_frames or int(settings.video_max_frames),
            )
            warnings.extend(extracted.warnings)

            registered_bgr = None
            registered_b64 = payload.registered_photo_base64 or payload.id_image_base64
            if registered_b64:
                registered = decode_base64_image(
                    registered_b64, max_bytes=int(settings.face_max_image_bytes)
                )
                registered_bgr = registered.bgr

            engine = get_face_engine()
            result = await asyncio.to_thread(
                engine.analyze,
                registered_bgr=registered_bgr,
                live_frames_bgr=extracted.frames_bgr,
            )
            warnings.extend(result.warnings)

        except VideoFrameError as exc:
            return VideoIntelligenceResponse(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id,
                status=JobStatus.FAILED,
                stub=False,
                message=str(exc),
                verified=False,
                consent_recorded=True,
                deps_ok=True,
                error_code=exc.code,
                warnings=warnings + [str(exc)],
                analysis_completeness="biometric_only",
            )
        except FaceImageError as exc:
            return VideoIntelligenceResponse(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id,
                status=JobStatus.FAILED,
                stub=False,
                message=str(exc),
                verified=False,
                consent_recorded=True,
                deps_ok=True,
                error_code=exc.code,
                warnings=warnings + [str(exc)],
                analysis_completeness="biometric_only",
            )
        except Exception as exc:  # noqa: BLE001
            logger.exception("Video intelligence failed")
            return VideoIntelligenceResponse(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id,
                status=JobStatus.FAILED,
                stub=False,
                message=f"Video analysis failed: {type(exc).__name__}",
                verified=False,
                consent_recorded=True,
                deps_ok=True,
                error_code="engine_error",
                warnings=warnings + [f"{type(exc).__name__}: {exc}"],
                analysis_completeness="biometric_only",
            )
        finally:
            if extracted is not None:
                frames = list(extracted.frames_bgr)
                frame_indices = list(extracted.frame_indices)
                timestamps_ms = list(extracted.timestamps_ms)
                duration = extracted.duration_seconds
                source_fps = extracted.source_fps
                sample_fps = extracted.sample_fps
                extracted.cleanup()
            else:
                frames = []
                frame_indices = []
                timestamps_ms = []
                duration = None
                source_fps = None
                sample_fps = payload.sample_fps

        assert result is not None

        identity = IdentityMatchResult(
            matched=result.identity_matched,
            match_score=result.match_score,
            distance=result.distance,
            threshold=result.threshold,
            model=result.model,
            error_code=(
                None
                if result.identity_matched
                else (
                    "identity_not_requested"
                    if result.identity_matched is None
                    else (
                        result.error_code
                        if result.error_code
                        not in {"liveness_failed", "liveness_and_identity_failed"}
                        else "identity_mismatch"
                    )
                )
            ),
        )
        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"
            )
        liveness = 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,
        )

        # verified = identity match + liveness. Identity-not-requested ⇒ verified false.
        verified = bool(
            result.identity_matched is True and result.liveness_passed is True
        )
        # Analysis can still succeed on liveness-only (no photo) when liveness passes.
        analysis_ok = bool(result.liveness_passed) and (
            result.identity_matched is not False
        )

        face_ratio = result.faces_detected_ratio or 0.0
        live_score = result.liveness_score or 0.0
        identity_signal = 0.1 if result.identity_matched is True else 0.0
        engagement = round(
            min(1.0, 0.55 * face_ratio + 0.35 * live_score + identity_signal),
            4,
        )
        signals = [
            VideoSignal(
                name="face_presence",
                score=round(face_ratio, 4),
                notes=f"Faces detected in {face_ratio * 100:.0f}% of sampled frames",
            ),
            VideoSignal(
                name="liveness",
                score=round(live_score, 4),
                notes="Anti-spoof score (DeepFace FasNet-class)",
            ),
            VideoSignal(
                name="single_face_stability",
                score=round(
                    max(0.0, 1.0 - (result.multi_face_frames / max(1, len(frames)))),
                    4,
                ),
                notes=f"{result.multi_face_frames} multi-face frame(s)",
            ),
        ]
        if result.identity_matched is not None:
            signals.append(
                VideoSignal(
                    name="identity_match",
                    score=result.match_score,
                    notes="ArcFace match vs registered photo",
                )
            )

        # Pad indices/timestamps if engine returned fewer/more frame rows
        while len(frame_indices) < len(result.frame_results):
            frame_indices.append(len(frame_indices))
            timestamps_ms.append(None)
        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,
                frame_index=frame_indices[i] if i < len(frame_indices) else None,
                timestamp_ms=timestamps_ms[i] if i < len(timestamps_ms) else None,
            )
            for i, fr in enumerate(result.frame_results)
        ]

        visual_events, quality_obs = build_visual_events(
            frame_results=result.frame_results,
            frame_indices=frame_indices[: len(result.frame_results)],
            timestamps_ms=timestamps_ms[: len(result.frame_results)],
        )

        # Optional transcript (FFmpeg demux → existing TranscriptionService)
        transcript_bundle: VideoTranscriptBundle | None = None
        segments = []
        partial = False
        if payload.include_transcript:
            transcript_bundle, tx_warns, tx_limits = await self._optional_transcript(
                payload=payload,
                video_bytes=video_bytes or b"",
            )
            warnings.extend(tx_warns)
            limitations.extend(tx_limits)
            if transcript_bundle and transcript_bundle.error_code:
                partial = True
            # Missing segments (no synthesis) ⇒ partial; approximate segments still align
            if "transcript_segments_missing" in tx_limits:
                partial = True
            segments = list(transcript_bundle.segments) if transcript_bundle else []
        else:
            limitations.append("Transcript not requested (include_transcript=false)")

        try:
            highlights = build_highlights(
                visual_events=visual_events,
                segments=segments,
                interview_topics=payload.interview_topics,
            )
        except Exception as exc:  # noqa: BLE001
            logger.warning("Highlight alignment failed: %s", exc)
            highlights = []
            warnings.append(f"highlights_failed: {type(exc).__name__}")
            limitations.append("highlights_failed")
            if payload.include_transcript or payload.include_report:
                partial = True

        report = None
        if payload.include_report:
            metadata = {
                "frames_analyzed": len(frames),
                "duration_seconds": duration,
                "source_fps": source_fps,
                "sample_fps": sample_fps,
            }
            proc_status = "complete"
            if not analysis_ok:
                proc_status = "partial"
            if partial or (
                payload.include_transcript
                and transcript_bundle
                and transcript_bundle.error_code
            ):
                proc_status = "partial"
            try:
                report, _report_stub = await build_report(
                    interview_id=payload.interview_id,
                    metadata=metadata,
                    visual_events=visual_events,
                    highlights=highlights,
                    segments=segments,
                    transcript_text=transcript_bundle.text if transcript_bundle else None,
                    quality=quality_obs,
                    faces_detected_ratio=result.faces_detected_ratio,
                    multi_face_frames=result.multi_face_frames,
                    frames_analyzed=len(frames),
                    identity_matched=result.identity_matched,
                    liveness_passed=result.liveness_passed,
                    verified=verified,
                    limitations=limitations,
                    processing_status=proc_status,
                )
            except Exception as exc:  # noqa: BLE001
                logger.warning("Report build failed: %s", exc)
                report = None
                warnings.append(f"report_failed: {type(exc).__name__}")
                limitations.append("report_failed")
                partial = True
        else:
            limitations.append("Structured report not requested (include_report=false)")

        if payload.include_transcript or payload.include_report:
            completeness = "partial" if partial or not analysis_ok else "full"
        else:
            completeness = "biometric_only"

        error_code = None if analysis_ok else (result.error_code or "checks_failed")
        elapsed_ms = (time.perf_counter() - t0) * 1000.0
        metrics.observe_ms("video_intelligence.latency_ms", elapsed_ms)
        metrics.incr("video_intelligence.frames_sampled", len(frames))
        if analysis_ok:
            metrics.incr("video_intelligence.succeeded")
        else:
            metrics.incr("video_intelligence.failed")
        # Structured ops log — no base64 / biometrics
        logger.info(
            "video_intelligence done interview_id=%s frames=%s verified=%s "
            "analysis_ok=%s error_code=%s elapsed_ms=%.1f",
            payload.interview_id,
            len(frames),
            verified,
            analysis_ok,
            error_code,
            elapsed_ms,
        )
        return VideoIntelligenceResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED if analysis_ok else JobStatus.FAILED,
            stub=False,
            message=(
                "Video intelligence analysis complete"
                if analysis_ok
                else f"Video analysis incomplete: {error_code}"
            ),
            frames_analyzed=len(frames),
            duration_seconds=duration,
            source_fps=source_fps,
            sample_fps=sample_fps,
            faces_detected_ratio=result.faces_detected_ratio,
            multi_face_frames=result.multi_face_frames,
            identity=identity,
            liveness=liveness,
            identity_matched=result.identity_matched,
            liveness_passed=result.liveness_passed,
            match_score=result.match_score,
            liveness_score=result.liveness_score,
            frame_results=frame_results,
            verified=verified,
            consent_recorded=True,
            model=result.model,
            detector=result.detector,
            deps_ok=True,
            engagement_score=engagement,
            signals=signals,
            error_code=error_code,
            warnings=warnings,
            analysis_completeness=completeness,  # type: ignore[arg-type]
            visual_events=visual_events,
            transcript=transcript_bundle,
            highlights=highlights,
            report=report,
        )

    async def _optional_transcript(
        self,
        *,
        payload: VideoIntelligenceRequest,
        video_bytes: bytes,
    ) -> tuple[VideoTranscriptBundle, list[str], list[str]]:
        warns: list[str] = []
        limits: list[str] = []
        demuxed = None
        audio_duration_ms: int | None = None
        try:
            demuxed = await asyncio.to_thread(
                extract_audio_wav_from_video,
                video_bytes,
            )
            warns.extend(demuxed.warnings)
            audio_duration_ms = wav_duration_ms(demuxed.wav_bytes)
            audio_b64 = base64.b64encode(demuxed.wav_bytes).decode("ascii")
        except VideoAudioError as exc:
            limits.append(exc.code)
            return (
                VideoTranscriptBundle(
                    text=None,
                    segments=[],
                    error_code=exc.code,
                    message=str(exc),
                ),
                warns,
                limits,
            )
        finally:
            if demuxed is not None:
                demuxed.cleanup()

        opts = dict(payload.options or {})
        opts.setdefault("mime_type", "audio/wav")
        raw_provider = str(opts.get("transcript_provider") or "openai").lower()
        if raw_provider in {"stub", "local", "mock"}:
            provider = TranscriptionProvider.STUB
            if not opts.get("stub_transcript"):
                warns.append(
                    "Stub STT will use placeholder text unless options.stub_transcript "
                    "is set (dev/test only)"
                )
        elif raw_provider in {"whisper"}:
            provider = TranscriptionProvider.WHISPER
        elif raw_provider in {"openai"}:
            provider = TranscriptionProvider.OPENAI
        else:
            warns.append(
                f"Unknown transcript_provider={raw_provider!r}; using openai"
            )
            provider = TranscriptionProvider.OPENAI

        # Timed segments are required for transcript↔visual highlight alignment.
        # gpt-4o-*-transcribe returns text only — prefer whisper-1 unless overridden.
        if provider != TranscriptionProvider.STUB:
            opts.setdefault("require_segments", True)
            if not opts.get("transcription_model") and not opts.get("model"):
                opts["transcription_model"] = str(
                    opts.get("segment_model") or "whisper-1"
                )
                warns.append(
                    "Using whisper-1 for timed transcript segments "
                    "(override with options.transcription_model)"
                )

        tx_req = TranscriptionRequest(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            provider=provider,
            audio_base64=audio_b64,
            language=str(opts.get("language") or "en"),
            options=opts,
        )
        try:
            tx = await TranscriptionService().transcribe(tx_req)
        except Exception as exc:  # noqa: BLE001
            logger.warning("Transcript step failed: %s", exc)
            limits.append("transcription_failed")
            return (
                VideoTranscriptBundle(
                    text=None,
                    segments=[],
                    error_code="transcription_failed",
                    message=str(exc),
                ),
                warns,
                limits,
            )

        text = (tx.text or "").strip() or None
        if tx.status != JobStatus.SUCCEEDED:
            code = tx.error_code or "transcription_failed"
            limits.append(code)
            return (
                VideoTranscriptBundle(
                    text=text,
                    segments=list(tx.segments or []),
                    provider=str(tx.provider.value) if tx.provider else None,
                    model=tx.model,
                    stub=bool(tx.stub),
                    error_code=code,
                    message=tx.message,
                ),
                warns,
                limits,
            )

        if not text:
            code = tx.error_code or "transcription_empty"
            limits.append(code)
            return (
                VideoTranscriptBundle(
                    text=None,
                    segments=list(tx.segments or []),
                    provider=str(tx.provider.value) if tx.provider else None,
                    model=tx.model,
                    stub=bool(tx.stub),
                    error_code=code,
                    message=tx.message or "STT returned empty transcript",
                ),
                warns,
                limits,
            )

        segments = list(tx.segments or [])
        if not segments:
            # Fallback: approximate timing from text + WAV duration so highlights
            # can still co-occur with visuals (not word-accurate).
            dur = audio_duration_ms
            if dur is None or dur <= 0:
                # Last resort: span unknown duration as a single 0–N window
                dur = max(2000, len(text) * 50)
            synth = synthesize_timed_segments(text, duration_ms=int(dur))
            if synth:
                segments = [
                    TranscriptSegment(
                        start_ms=int(s["start_ms"]),
                        end_ms=int(s["end_ms"]),
                        text=str(s.get("text") or ""),
                        confidence=s.get("confidence"),
                        speaker=s.get("speaker"),
                    )
                    for s in synth
                ]
                warns.append(
                    "STT returned no timestamps — synthesized approximate segments "
                    "from transcript text + audio duration for alignment"
                )
                limits.append("transcript_segments_approximate")
            else:
                warns.append(
                    "Transcript has no timed segments — alignment limited "
                    "(use whisper-1 / verbose_json capable model for segments)"
                )
                limits.append("transcript_segments_missing")

        return (
            VideoTranscriptBundle(
                text=text,
                segments=segments,
                provider=str(tx.provider.value) if tx.provider else None,
                model=tx.model,
                stub=bool(tx.stub),
                error_code=None,
                message=tx.message,
            ),
            warns,
            limits,
        )

    async def _load_source(self, source: str) -> bytes:
        """Load video from http(s) URL, or local path when VIDEO_ALLOW_LOCAL_SOURCE=true."""
        raw = (source or "").strip()
        if not raw:
            raise VideoFrameError(
                "source_url is empty — provide http(s) URL "
                "(or enable VIDEO_ALLOW_LOCAL_SOURCE for local/file paths)",
                code="invalid_source_url",
            )

        settings = get_settings()
        parsed = urlparse(raw)
        scheme = (parsed.scheme or "").lower()

        if scheme in {"http", "https"}:
            return await self._fetch_http(raw)

        if scheme == "file" or not scheme:
            if not bool(settings.video_allow_local_source):
                raise VideoFrameError(
                    "Local/file source_url is disabled "
                    "(set VIDEO_ALLOW_LOCAL_SOURCE=true for dev only)",
                    code="local_source_disabled",
                )
            if scheme == "file":
                path = unquote(parsed.path or "")
                if parsed.netloc and parsed.netloc not in {"localhost", "127.0.0.1", ""}:
                    path = f"/{parsed.netloc}{path}"
            else:
                path = raw
            return await asyncio.to_thread(self._read_local_file, path)

        raise VideoFrameError(
            f"Unsupported source_url scheme '{scheme}' — use http(s)",
            code="invalid_source_url",
        )

    @staticmethod
    def _read_local_file(path_str: str) -> bytes:
        settings = get_settings()
        max_bytes = int(settings.video_max_upload_bytes)
        try:
            path = Path(path_str).expanduser().resolve(strict=True)
        except FileNotFoundError as exc:
            raise VideoFrameError(
                f"Local video not found: {path_str}",
                code="source_not_found",
            ) from exc
        except OSError as exc:
            raise VideoFrameError(
                f"Cannot read local video path: {exc}",
                code="invalid_source_url",
            ) from exc

        if not path.is_file():
            raise VideoFrameError(
                f"source_url is not a file: {path}",
                code="invalid_source_url",
            )
        size = path.stat().st_size
        if size < 64:
            raise VideoFrameError("Local video file too small", code="invalid_video")
        if size > max_bytes:
            raise VideoFrameError(
                f"Local video exceeds max size ({max_bytes} bytes)",
                code="video_too_large",
            )
        data = path.read_bytes()
        if not looks_like_video_bytes(data):
            logger.info("Local source magic-byte sniff unmatched path=%s", path.name)
        return data

    async def _fetch_http(self, url: str) -> bytes:
        settings = get_settings()
        max_bytes = int(settings.video_max_upload_bytes)
        assert_public_http_url(url, resolve_dns=True)

        timeout = httpx.Timeout(
            timeout=float(settings.video_http_timeout_seconds),
            connect=float(settings.video_http_connect_timeout_seconds),
        )
        max_redirects = int(settings.video_http_max_redirects)

        try:
            async with httpx.AsyncClient(
                timeout=timeout,
                follow_redirects=False,
            ) as client:
                current = url
                for _ in range(max_redirects + 1):
                    assert_public_http_url(current, resolve_dns=True)
                    res = await client.get(current)
                    if res.status_code in {301, 302, 303, 307, 308}:
                        loc = res.headers.get("location")
                        if not loc:
                            raise VideoFrameError(
                                "Redirect without Location header",
                                code="source_fetch_failed",
                            )
                        # Resolve relative redirects against current URL
                        current = str(httpx.URL(current).join(loc))
                        continue
                    res.raise_for_status()
                    cl = res.headers.get("content-length")
                    if cl is not None:
                        try:
                            if int(cl) > max_bytes:
                                raise VideoFrameError(
                                    f"Remote video Content-Length exceeds max ({max_bytes} bytes)",
                                    code="video_too_large",
                                )
                        except ValueError:
                            pass
                    # Stream into memory with hard cap (videos are still fully needed for OpenCV)
                    chunks: list[bytes] = []
                    total = 0
                    async for chunk in res.aiter_bytes(chunk_size=64 * 1024):
                        total += len(chunk)
                        if total > max_bytes:
                            raise VideoFrameError(
                                f"Downloaded video exceeds max size ({max_bytes} bytes)",
                                code="video_too_large",
                            )
                        chunks.append(chunk)
                    data = b"".join(chunks)
                    break
                else:
                    raise VideoFrameError(
                        f"Too many redirects (max {max_redirects})",
                        code="ssrf_blocked",
                    )
        except VideoFrameError:
            metrics.incr("video_intelligence.source_fetch_failed")
            raise
        except httpx.UnsupportedProtocol as exc:
            metrics.incr("video_intelligence.source_fetch_failed")
            raise VideoFrameError(
                "source_url must start with http:// or https://",
                code="invalid_source_url",
            ) from exc
        except httpx.TimeoutException as exc:
            metrics.incr("video_intelligence.source_timeout")
            raise VideoFrameError(
                "Timed out downloading source_url",
                code="source_timeout",
            ) from exc
        except httpx.HTTPStatusError as exc:
            metrics.incr("video_intelligence.source_fetch_failed")
            raise VideoFrameError(
                f"Failed to download video (HTTP {exc.response.status_code})",
                code="source_fetch_failed",
            ) from exc
        except httpx.HTTPError as exc:
            metrics.incr("video_intelligence.source_fetch_failed")
            raise VideoFrameError(
                f"Failed to download video: {type(exc).__name__}",
                code="source_fetch_failed",
            ) from exc

        if len(data) < 64:
            raise VideoFrameError("Downloaded video too small", code="invalid_video")
        if not looks_like_video_bytes(data):
            logger.info("Downloaded bytes failed video magic-byte sniff")
        return data
