"""Structured video intelligence report from evidence (text LLM + local fallback).

Does not send video/frames to vision models — this repo's Gemini client is text-only.
Never invents timestamps, transcripts, or visual evidence.
"""

from __future__ import annotations

from typing import Any

from app.schemas.transcription import TranscriptSegment
from app.schemas.video_intelligence import (
    VideoHighlight,
    VideoIntelligenceReport,
    VideoQualityObservation,
    VisualEvent,
)
from app.services.shared.ai_generate import generate_json


def _face_presence_summary(
    *,
    faces_detected_ratio: float | None,
    multi_face_frames: int,
    frames_analyzed: int,
) -> str:
    ratio = faces_detected_ratio
    if ratio is None:
        return "Face-presence ratio unavailable"
    return (
        f"Faces detected in {ratio * 100:.0f}% of {frames_analyzed} sampled frames; "
        f"{multi_face_frames} multi-face frame(s)"
    )


def _verification_summary(
    *,
    identity_matched: bool | None,
    liveness_passed: bool | None,
    verified: bool | None,
) -> str:
    parts = [
        f"liveness={'passed' if liveness_passed else 'failed' if liveness_passed is False else 'n/a'}",
        f"identity={'matched' if identity_matched else 'mismatch' if identity_matched is False else 'not_requested'}",
        f"verified={verified}",
    ]
    return "; ".join(parts)


def _local_summary(
    *,
    interview_id: str,
    events: list[VisualEvent],
    segments: list[TranscriptSegment],
    limitations: list[str],
) -> str:
    labels = sorted({e.label for e in events})
    tx = "yes" if segments or False else "no"
    lim = f" Limitations: {'; '.join(limitations)}" if limitations else ""
    return (
        f"Interview {interview_id}: sampled-frame CV observed labels "
        f"{labels or ['none']}; transcript_available={tx}.{lim} "
        "Summary is evidence-linked aggregation — not a hiring recommendation."
    )


async def build_report(
    *,
    interview_id: str,
    metadata: dict[str, Any],
    visual_events: list[VisualEvent],
    highlights: list[VideoHighlight],
    segments: list[TranscriptSegment],
    transcript_text: str | None,
    quality: list[VideoQualityObservation],
    faces_detected_ratio: float | None,
    multi_face_frames: int,
    frames_analyzed: int,
    identity_matched: bool | None,
    liveness_passed: bool | None,
    verified: bool | None,
    limitations: list[str],
    processing_status: str,
) -> tuple[VideoIntelligenceReport, bool]:
    """Returns (report, used_llm_stub)."""

    excerpts = [s.text for s in segments[:8] if s.text]
    if not excerpts and transcript_text:
        excerpts = [transcript_text[:400]]

    event_lines = [
        f"{e.timestamp_ms}ms {e.label}: {e.evidence}" for e in visual_events[:40]
    ]
    hl_lines = [
        f"{h.start_ms}-{h.end_ms}ms [{h.relationship}] {h.description}"
        for h in highlights[:12]
    ]

    def local() -> dict[str, Any]:
        return {
            "summary": _local_summary(
                interview_id=interview_id,
                events=visual_events,
                segments=segments,
                limitations=limitations,
            ),
            "follow_up_items": (
                (
                    [
                        "Review multi-face or spoof_suspected moments with original recording",
                    ]
                    + (
                        [
                            "Confirm transcript accuracy around aligned timestamps",
                        ]
                        if segments
                        else []
                    )
                )
                if visual_events or segments
                else ["Re-run with clearer video/audio if analysis was empty"]
            ),
            "evidence_notes": [
                "Visual events are sampled-frame observations from face/quality CV",
                "Transcript alignment uses proximity only; co-occurrence ≠ causation",
                "No personality, honesty, or hiring suitability inferred from face/gaze",
            ]
            + (
                []
                if segments or transcript_text
                else ["No transcript excerpts — speech text was not available"]
            ),
        }

    system = (
        "You summarize interview video analysis evidence for recruiters. "
        "Return JSON: {\"summary\": str, \"follow_up_items\": [str], "
        "\"evidence_notes\": [str]}. "
        "Only use provided evidence. Do not invent timestamps or events. "
        "Do not infer honesty, personality, competence, or hiring fit from faces."
    )
    user = (
        f"interview_id={interview_id}\n"
        f"metadata={metadata}\n"
        f"visual_events:\n" + "\n".join(event_lines[:30]) + "\n"
        f"highlights:\n" + "\n".join(hl_lines[:12]) + "\n"
        f"transcript_excerpts:\n" + "\n".join(excerpts[:6]) + "\n"
        f"limitations={limitations}"
    )

    data, stub, _provider = await generate_json(
        system=system, user=user, local_factory=local
    )

    summary = data.get("summary")
    if not isinstance(summary, str) or not summary.strip():
        summary = local()["summary"]
        stub = True

    follow = data.get("follow_up_items") or local()["follow_up_items"]
    if not isinstance(follow, list):
        follow = local()["follow_up_items"]
    notes = data.get("evidence_notes") or local()["evidence_notes"]
    if not isinstance(notes, list):
        notes = local()["evidence_notes"]

    status: str = processing_status
    if status not in {"complete", "partial", "failed"}:
        status = "partial"

    report = VideoIntelligenceReport(
        processing_status=status,  # type: ignore[arg-type]
        video_metadata=metadata,
        summary=summary.strip(),
        visual_observations=visual_events,
        transcript_excerpts=[str(x) for x in excerpts],
        highlights=highlights,
        face_presence_summary=_face_presence_summary(
            faces_detected_ratio=faces_detected_ratio,
            multi_face_frames=multi_face_frames,
            frames_analyzed=frames_analyzed,
        ),
        verification_summary=_verification_summary(
            identity_matched=identity_matched,
            liveness_passed=liveness_passed,
            verified=verified,
        ),
        quality_observations=quality,
        evidence_notes=[str(n) for n in notes],
        limitations=list(limitations),
        follow_up_items=[str(f) for f in follow],
        summary_source="local" if stub else "llm",
    )
    return report, stub
