
from typing import List, Optional 
from pydantic import BaseModel
from fastapi import APIRouter, Body
from fastapi.responses import JSONResponse

from app.utils.utils import Utils



router = APIRouter(prefix="/video", tags=["Youtube Video Comments Analyzer"])

class VideoAnalysisRequest(BaseModel):
    videoURL: str
    nbrComments: Optional[int] = 1000


@router.post("/comments")
async def get_comments(request: VideoAnalysisRequest):
    try:
        videoURL = request.videoURL
        nbrComments = request.nbrComments

        # Validate the videoURL is Not None or Empty
        if videoURL is None or not videoURL.strip():
            return JSONResponse(
                {"message": "YouTube video URL parameter is required!", "status": "error"},
                status_code=400 
            )

        # Validate the YouTube URL
        if not Utils.validate_youtube_url(videoURL):
            return JSONResponse(
                {"message": "Invalid YouTube URL", "status": "error"},
                status_code=400
            ) 
        
        # Extract video ID from the URL
        extract_id = Utils.extract_video_id(videoURL)

        if not extract_id["status"]:
            return JSONResponse(
                {"message": extract_id["message"], "status": "error"},
                status_code=400
            ) 
            
        # video ID  
        video_id = extract_id["data"]
        
        # Extract Video Comments 
        extract_comments = Utils.get_youtube_comments(video_id=video_id, nbr_comments=nbrComments,) 

        if not extract_comments["status"]:
            return JSONResponse(
                {"message": extract_id["message"], "status": "error"},
                status_code=400
            ) 
        
        # Comments
        comments = extract_comments["data"] 

        return JSONResponse(
            {
                "videoID"      : video_id, 
                "videoURL"     : f'https://www.youtube.com/watch?v={video_id}', 
                "nbr_comments" : nbrComments, 
                "comments"     : comments, 
                "status"       : "success"
            },
            status_code=200
        )
 

    except Exception as ex:
        return JSONResponse(
            {"message": str(ex), "status": "error"},
            status_code=400
        )
    

@router.post("/analyse")
async def analyse(request: VideoAnalysisRequest):
    try:
        videoURL = request.videoURL
        nbrComments = request.nbrComments

        # Validate the videoURL is Not None or Empty
        if videoURL is None or not videoURL.strip():
            return JSONResponse(
                {"message": "YouTube video URL parameter is required!", "status": "error"},
                status_code=400 
            )

        # Validate the YouTube URL
        if not Utils.validate_youtube_url(videoURL):
            return JSONResponse(
                {"message": "Invalid YouTube URL", "status": "error"},
                status_code=400
            ) 
        
        # Extract video ID from the URL
        extract_id = Utils.extract_video_id(videoURL)

        if not extract_id["status"]:
            return JSONResponse(
                {"message": extract_id["message"], "status": "error"},
                status_code=400
            ) 
            
        # video ID  
        video_id = extract_id["data"]
        
        # Extract Video Comments 
        extract_comments = Utils.get_youtube_comments(video_id=video_id, nbr_comments=nbrComments,) 

        if not extract_comments["status"]:
            return JSONResponse(
                {"message": extract_id["message"], "status": "error"},
                status_code=400
            ) 
        
        # Comments
        comments = extract_comments["data"]

        # Reporting Logic => Split comments & create report for each comments chunk using definded prompt with open-ai API.
        reports = Utils.get_comments_reports(comment_list=comments) 
        
        # Merge All Reports To Get A Final Report with Comments Sentiments Analysis 
        final_report = Utils.summarize_reports(reports)   
        
        # generate a summarize in json format to present Comments Sentiments Analysis for the given video 
        summarize = Utils.define_summary(final_report)

        return JSONResponse(
            {
                "videoID"      : video_id, 
                "videoURL"     : f'https://www.youtube.com/watch?v={video_id}', 
                "nbr_comments" : nbrComments, 
                "comments"     : comments,
                "report"       : summarize,
                "status"       : "success"
            },
            status_code=200
        )
 

    except Exception as ex:
        return JSONResponse(
            {"message": str(ex), "status": "error"},
            status_code=400
        )