"""
Video processing service using Tortoise ORM with streaming S3 processing.
"""

from typing import Any

from app.core.logging import get_logger
from app.repositories.feedback_repository import FeedbackRepository
from app.services.progress_tracker import ProcessingStep, ProgressTracker
from app.utils.processing_runner import process_s3_file

logger = get_logger("video_processor")


class VideoProcessor:
    """Service for processing video files using streaming S3 approach."""

    def __init__(self):
        pass

    async def process_video(
        self,
        job_id: str,
        user_id: int,
        interview_id: int,
        question_id: int,
        interview_type: str,
        video_path: str,
    ) -> dict[str, Any]:
        """Process video file for AI feedback analysis using streaming S3 processing."""
        try:
            logger.info(
                f"[JOB {job_id}] Video processor started | "
                f"user_id={user_id} interview_id={interview_id} question_id={question_id}"
            )

            # Use streaming S3 processing instead of downloading
            async def _analyze_video_streaming(local_path: str) -> dict[str, Any]:
                # Update progress for video analysis start
                await ProgressTracker.update_progress(
                    job_id, ProcessingStep.ANALYZING_VISUAL
                )

                return await self._analyze_video_content(
                    local_path,
                    user_id,
                    interview_id,
                    question_id,
                    interview_type,
                    job_id,
                )

            # Use whole file download for all video files to avoid chunking issues
            analysis_result = await process_s3_file(
                job_id,
                "video",
                video_path,
                _analyze_video_streaming,
                cleanup=True,
            )

            # Store results in database
            logger.info(f"[JOB {job_id}] Saving video analysis results to database")
            feedback_repo = FeedbackRepository()
            await feedback_repo.upsert_feedback_json(
                user_id=user_id,
                interview_id=interview_id,
                question_id=question_id,
                interview_type=interview_type,
                content_json=analysis_result,
            )
            logger.info(f"[JOB {job_id}] Video analysis results saved successfully")

            # Cleanup handled by processing runner

            logger.info(f"[JOB {job_id}] Video processing completed successfully")

            return {
                "status": "success",
                "message": "Streaming video processing completed successfully",
                "job_id": job_id,
                "analysis_result": analysis_result,
                "processing_method": "streaming_s3",
                # Legacy duration equals formatted audio length (MM:SS)
                "duration": analysis_result.get("audio_length", "0"),
            }

        except Exception as e:
            logger.error(f"Streaming video processing failed for job {job_id}: {e}")
            raise e

    async def _analyze_video_content(
        self,
        video_path: str,
        user_id: int,
        interview_id: int,
        question_id: int,
        interview_type: str,
        job_id: str,
    ) -> dict[str, Any]:
        """Analyze video content using comprehensive analysis service."""
        try:
            from app.services.video_analysis import (
                VideoAnalysisService,
            )

            # Initialize comprehensive analysis service
            analyzer = VideoAnalysisService()

            # Perform comprehensive analysis with progress tracking
            analysis_result = await analyzer.analyze_video(
                video_path,
                user_id=user_id,
                interview_id=interview_id,
                question_id=question_id,
                interview_type=interview_type,
                job_id=job_id,
            )

            return analysis_result

        except Exception as e:
            logger.error(f"Video content analysis failed: {e}")
            raise e
