import sys
import os
import requests
import json
from duckduckgo_search import DDGS
import yt_dlp
import xml.etree.ElementTree as ET
from app import db, Video, create_app

LANGS = ['en', 'zh-Hans']

def process_video(video_id):
    db1, app = create_app()
    with app.app_context():
        video = Video.query.get(video_id)
        if not video:
            return
        
        try:
            video.status = 'downloading'
            db.session.commit()
            video_info = download_video(video.url)
            video.status = 'summarizing'
            db.session.commit()
            

            try:
                video.subtitle = video_info['subtitles']['en']
                video.summary = summarize_video(video.subtitle)
            except KeyError:
                pass
            try:
                video.subtitle_zh = video_info['subtitles']['zh-Hans']
                video.summary_zh = summarize_video_zh(video.subtitle_zh)
            except KeyError:
                pass
            video.filename = f"{video_info['id']}.mp4"
            video.title = video_info['title']
            video.status = 'completed'
            db.session.commit()
        except Exception as e:
            video.status = 'failed'
            video.subtitle = f"Error: {str(e)}"
            video.subtitle_zh = f"Error: {str(e)}"
            video.summary = f"Error: {str(e)}"
            video.summary_zh = f"Error: {str(e)}"
            db.session.commit()

def post_your_prompt(prompt, srv="none", model = "llama3.1", key = "none"):
    data = {
        "model": model,
        "prompt": prompt,
        "stream": True,
    }
    headers = {
        'Authorization': 'Bearer ' +key,
        'Content-Type': 'application/json'
    }
    response_text = ""
    buffer = ""

    with requests.post(srv, json=data,  headers=headers, stream=True) as response:
        response.raise_for_status()
        for json_chunk in response.iter_content(chunk_size=1024):
            if json_chunk:
                buffer += json_chunk.decode('utf-8')
                try:
                    line = json.loads(buffer)
                    if 'response' in line:
                        print(line['response'], end="", flush=True)
                        response_text += line['response']
                    buffer = ""
                except json.JSONDecodeError:
                    continue
           
    print("\n")
    return response_text

def ask_chat1(prompt, model="llama3.1:70b"):
    return post_your_prompt(prompt,  srv="https://chat.g77k.com/ollama/api/generate", model=model, key ="sk-9f483b1bc0b24098a48b2966b151406a")

def ask_chat1_mistral(prompt, model="mistral-large"):
    return post_your_prompt(prompt,  srv="https://chat.g77k.com/ollama/api/generate", model=model, key ="sk-9f483b1bc0b24098a48b2966b151406a")

def ask_chat2(prompt, model="llama3.1"):
    return post_your_prompt(prompt,  srv="https://chat2.g77k.com/ollama/api/generate", model=model, key="sk-3ec8d27821f643fb97aedd589062ebbc")

def ask_chat2_qwen2(prompt, model="qwen2"):
    return post_your_prompt(prompt,  srv="https://chat2.g77k.com/ollama/api/generate", model=model, key="sk-3ec8d27821f643fb97aedd589062ebbc")

def search_ddgs(q):
    news_body = []
    with DDGS() as ddgs:
        for r in ddgs.news(q, region='wt-wt', safesearch='off', timelimit='m', max_results=30):
            news_body.append(r['body'])
            print(r['body'])
    return "\n".join(news_body)


def download_video(url):
    # Define options for yt-dlp
    ydl_opts = {
        'writesubtitles': True,         # Enable subtitle download
        'subtitleslangs': LANGS,        # Download subtitles in English and Chinese (Simplified)
        'subtitlesformat': 'srv1',      # Choose subtitle format
        'skip_download': False,         # Download the video
        'writeautomaticsub': True,      # Download auto-generated subtitles
        'outtmpl': 'data/%(id)s.%(ext)s', # Use video ID as filename template
        'writethumbnail': True,         # Download thumbnail
        'cookies': '/opt/cookies.txt',  # Path to your cookies.txt file
        'writesubtitles': True,
        'writeinfojson': True,          # Write metadata info to a JSON file
        'getcomments': True,            # Extract and save comments
        'getrecommended': True,         # Fetch recommended videos
    }

    video_id = ""
    video_title = ""
    subtitles = {}

    # Download subtitles
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        video_title = ydl.extract_info(url, download=False).get('title', None)
        info_dict = ydl.extract_info(url, download=False)
        video_id = info_dict.get('id', None)
        ydl.download([url])
        
        for lang in LANGS:
            subtitle_file = f"data/{video_id}.{lang}.srv1"
            if os.path.exists(subtitle_file):
                with open(subtitle_file, 'r', encoding='utf-8') as file:
                    xml_content = file.read()
                
                # Parse the XML content to extract pure text
                root = ET.fromstring(xml_content)
                subtitle = ", ".join([elem.text for elem in root.iter('text') if elem.text])
                subtitle = subtitle.replace("&#39;", "'")
                subtitles[lang] = subtitle
                print(f"Subtitles for {lang} read and extracted into variable successfully.")
            else:
                print(f"Subtitle file for {lang} not found.")
        
        # Load comments
        comments_file = f"data/{video_id}.comments.json"
        if os.path.exists(comments_file):
            with open(comments_file, 'r', encoding='utf-8') as file:
                comments = json.load(file)
                print("Comments downloaded and saved successfully.")
        else:
            print("Comments file not found.")

        # Load recommended videos
        recommended_file = f"data/{video_id}.recommend.json"
        if os.path.exists(recommended_file):
            with open(recommended_file, 'r', encoding='utf-8') as file:
                recommended_videos = json.load(file)
                print("Recommended videos fetched successfully.")
        else:
            print("Recommended videos file not found.")

    ret = {
        'id': video_id,
        'title': video_title,
        'subtitles': subtitles,
        'comments': comments,
        'recommended_videos': recommended_videos,
    }
    return ret

def summarize_video(subtitle):
    prompt = "Summarize this YouTube transcript for me, use some bullet points and emoji:\n" + subtitle
    response = ask_chat2(prompt)
    summary = response.replace("&#39;", "'")
    return summary

def summarize_video_zh(subtitle):
    prompt = "以下是个youtube的字幕，帮我总结下，并用标题，自标题，和emoji:\n" + subtitle
    response = ask_chat2(prompt)
    summary = response.replace("&#39;", "'")
    return summary
