"""Timed transcript segments for video↔speech alignment."""

from __future__ import annotations

from unittest.mock import AsyncMock, MagicMock, patch

from app.services.voice.segment_util import synthesize_timed_segments
from app.services.voice.stt_openai import (
    OpenAISTTProvider,
    _model_supports_segments,
    _parse_segments,
    _response_format_for_model,
)
from app.services.video.audio_demux import wav_duration_ms
from app.services.voice.wav_util import build_silent_wav


def test_whisper_uses_verbose_json_for_segments() -> None:
    assert _response_format_for_model("whisper-1") == "verbose_json"
    assert _model_supports_segments("whisper-1") is True
    assert _response_format_for_model("gpt-4o-mini-transcribe") == "json"
    assert _model_supports_segments("gpt-4o-mini-transcribe") is False


def test_parse_verbose_json_segments() -> None:
    body = {
        "text": "Hello world. Next.",
        "segments": [
            {"start": 0.0, "end": 1.2, "text": " Hello world."},
            {"start": 1.2, "end": 2.5, "text": " Next."},
        ],
    }
    segs = _parse_segments(body)
    assert len(segs) == 2
    assert segs[0]["start_ms"] == 0
    assert segs[0]["end_ms"] == 1200
    assert "Hello" in segs[0]["text"]


def test_parse_word_timestamps_coalesce() -> None:
    body = {
        "text": "one two three four",
        "words": [
            {"word": "one", "start": 0.0, "end": 0.3},
            {"word": "two", "start": 0.3, "end": 0.6},
            {"word": "three", "start": 0.6, "end": 0.9},
            {"word": "four", "start": 2.1, "end": 2.4},
        ],
    }
    segs = _parse_segments(body)
    assert segs
    assert segs[0]["start_ms"] == 0
    assert any("four" in s["text"] for s in segs)


def test_synthesize_timed_segments_spans_duration() -> None:
    text = "First sentence. Second sentence. Third one!"
    segs = synthesize_timed_segments(text, duration_ms=9000)
    assert len(segs) == 3
    assert segs[0]["start_ms"] == 0
    assert segs[-1]["end_ms"] == 9000
    assert all(s["end_ms"] > s["start_ms"] for s in segs)
    assert "First" in segs[0]["text"]


def test_wav_duration_ms() -> None:
    wav = build_silent_wav(duration_ms=1500, sample_rate=16000)
    dur = wav_duration_ms(wav)
    assert dur is not None
    assert 1400 <= dur <= 1600


def test_openai_stt_require_segments_forces_whisper_model() -> None:
    import asyncio

    provider = OpenAISTTProvider()
    captured: dict = {}

    async def fake_post(url, **kwargs):  # noqa: ANN003
        captured["files"] = kwargs.get("files")
        res = MagicMock()
        res.status_code = 200
        res.json.return_value = {
            "text": "Hello there.",
            "segments": [{"start": 0.0, "end": 1.0, "text": " Hello there."}],
        }
        return res

    async def _run() -> None:
        with patch("app.services.voice.stt_openai.get_settings") as gs:
            gs.return_value.openai_api_key = "sk-test"
            with patch(
                "app.services.voice.stt_openai.get_transcription_model",
                return_value="gpt-4o-mini-transcribe",
            ):
                with patch("httpx.AsyncClient") as client_cls:
                    instance = AsyncMock()
                    instance.__aenter__.return_value = instance
                    instance.__aexit__.return_value = None
                    instance.post = AsyncMock(side_effect=fake_post)
                    client_cls.return_value = instance

                    result = await provider.transcribe(
                        audio_bytes=build_silent_wav(
                            duration_ms=500, sample_rate=16000
                        ),
                        options={"require_segments": True},
                    )
        assert result.segments
        # Multipart fields are (name, (filename|None, value, ...))
        form = {
            name: (part[1] if isinstance(part, tuple) else part)
            for name, part in (captured["files"] or [])
        }
        assert form["model"] == "whisper-1"
        assert form["response_format"] == "verbose_json"
        assert form["timestamp_granularities[]"] == "segment"

    asyncio.run(_run())


def test_video_intel_synthesizes_segments_when_stt_omits_timestamps() -> None:
    """Integration: empty STT segments → approximate segments → co_occurring possible."""
    from fastapi.testclient import TestClient

    from app.config import get_settings
    from app.main import app
    from app.schemas.common import JobStatus
    from app.schemas.transcription import TranscriptionProvider, TranscriptionResponse
    from app.services.face.engine import FaceAnalysisEngine, FaceEngineResult, FrameAnalysis, set_face_engine_override
    from app.services.video.audio_demux import DemuxedAudio
    import base64
    import io
    from pathlib import Path

    import cv2
    import numpy as np
    from PIL import Image

    class FakeEngine(FaceAnalysisEngine):
        name = "fake"

        def analyze(self, *, registered_bgr, live_frames_bgr) -> FaceEngineResult:
            n = max(1, len(live_frames_bgr))
            frames = [
                FrameAnalysis(
                    face_count=1,
                    is_real=True,
                    antispoof_score=0.9,
                    faces_detected=True,
                )
                for _ in range(n)
            ]
            return FaceEngineResult(
                identity_matched=None,
                distance=None,
                threshold=None,
                match_score=None,
                liveness_passed=True,
                liveness_score=0.9,
                liveness_frame_pass_ratio=1.0,
                model="ArcFace",
                detector="opencv",
                face_count=1,
                frame_results=frames,
                faces_detected_ratio=1.0,
            )

    def _video_b64() -> str:
        path = Path("/tmp/tj_seg_align.avi")
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(str(path), fourcc, 4.0, (80, 80))
        for i in range(4):
            writer.write(np.full((80, 80, 3), (40 + i, 100, 150), dtype=np.uint8))
        writer.release()
        data = path.read_bytes()
        path.unlink(missing_ok=True)
        return base64.b64encode(data).decode("ascii")

    wav = build_silent_wav(duration_ms=6000, sample_rate=16000)
    demux = DemuxedAudio(wav_bytes=wav, warnings=[])

    async def _tx(self, payload):  # noqa: ANN001
        return TranscriptionResponse(
            interview_id=payload.interview_id,
            provider=TranscriptionProvider.OPENAI,
            model="gpt-4o-mini-transcribe",
            status=JobStatus.SUCCEEDED,
            stub=False,
            message="OK",
            text="I led the project. Then we shipped.",
            segments=[],  # no timestamps from model
        )

    set_face_engine_override(FakeEngine())
    client = TestClient(app)
    headers = {"X-Internal-Token": get_settings().internal_api_token}
    try:
        with patch(
            "app.services.video.intelligence.extract_audio_wav_from_video",
            return_value=demux,
        ), patch(
            "app.services.video.intelligence.TranscriptionService.transcribe",
            _tx,
        ):
            res = client.post(
                "/api/v1/video-intelligence",
                headers=headers,
                json={
                    "interview_id": "vid-seg-synth",
                    "video_base64": _video_b64(),
                    "consent_given": True,
                    "include_transcript": True,
                    "options": {"transcript_provider": "openai"},
                },
            )
        body = res.json()
        assert body["transcript"]["text"]
        assert body["transcript"]["segments"]
        assert body["transcript"]["segments"][0]["start_ms"] is not None
        assert "transcript_segments_approximate" in (body.get("warnings") or []) or any(
            "approximate" in w.lower() for w in (body.get("warnings") or [])
        )
        # Highlights should be able to attach transcript when segments exist
        assert any(
            h.get("transcript_excerpt") or h.get("relationship") in {"co_occurring", "uncertain", "visual_only", "transcript_only"}
            for h in body.get("highlights") or []
        )
    finally:
        set_face_engine_override(None)
