"""Video intelligence analysis."""

from app.schemas.common import JobStatus
from app.schemas.video_intelligence import (
    VideoIntelligenceRequest,
    VideoIntelligenceResponse,
    VideoSignal,
)
from app.services.ai_generate import generate_json


class VideoIntelligenceService:
    async def analyze(self, payload: VideoIntelligenceRequest) -> VideoIntelligenceResponse:
        system = (
            "Estimate engagement signals for an interview video. "
            "Return JSON: {\"engagement_score\":0-1,\"signals\":[{\"name\",\"score\",\"notes\"}],\"warnings\":[]}"
        )
        user = (
            f"Interview: {payload.interview_id}\nsample_fps={payload.sample_fps}\n"
            f"source={'base64' if payload.video_base64 else payload.source_url}"
        )

        def local() -> dict:
            return {
                "engagement_score": 0.7,
                "signals": [
                    {"name": "eye_contact", "score": 0.72, "notes": "Mostly facing camera"},
                    {"name": "attention", "score": 0.68, "notes": "Stable framing"},
                ],
                "warnings": [],
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        signals = [
            VideoSignal(
                name=str(s.get("name", "")),
                score=s.get("score"),
                notes=s.get("notes"),
            )
            for s in (data.get("signals") or [])
            if isinstance(s, dict)
        ]
        return VideoIntelligenceResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Video intelligence via {provider}",
            engagement_score=data.get("engagement_score"),
            signals=signals,
            warnings=list(data.get("warnings") or []),
        )
