from ..imports import *
from ..modules import *
def extract_keywords(text, top_n=10):
    try:
        kws = [kw for kw, _ in get_extract_keywords(
            text, keyphrase_ngram_range=(1,2), stop_words="english", top_n=top_n
        )]
        return list(dict.fromkeys(kws))  # dedup, preserve order
    except Exception as e:
        logger.warning(f"Keyword extraction failed: {e}")
        return []

def generate_title(text):
    try:
        out = get_summarizer(
            text,
            max_length=15,
            min_length=5,
            truncation=True,
            num_beams=4
            )[0]["summary_text"]
        return out.strip()
    except Exception:
        kws = extract_keywords(text, top_n=1)
        return kws[0].title() if kws else "Untitled"
def derive_video_metadata(
    video_path: str,
    repo_dir: str,
    domain: str,
    transcript:str
    ) -> dict:
    """
    Derive title, keywords, category, and thumbnail URL from a video.

    Args:
        video_path (str): Path to the video file.
        repo_dir (str): Local repo directory (root for media storage).
        domain (str): Public domain for media URLs, e.g. "https://abstractendeavors.com".

    Returns:
        dict with keys: title, keywords, category, thumbnail_url
    """

    # 1. Transcribe
    # 2. Summarize → Draft Title
    summary = get_summary(transcript, summary_mode="medium")
    generator = get_generator()
    title = refine_with_gpt(summary, task="title", generator_fn=generator)

    # 3. Keywords
    keyword_data = refine_keywords(transcript, top_n=12)
    keywords = keyword_data["combined_keywords"]

    # 4. Category (simple rules)
    def choose_category(kws):
        if any(k in kws for k in ["comedy", "skit", "funny", "humor"]):
            return "Comedy"
        if any(k in kws for k in ["news", "analysis", "report"]):
            return "News & Politics"
        if any(k in kws for k in ["music", "song", "album"]):
            return "Music"
        return "Entertainment"
    category = choose_category(keywords)

    # 5. Thumbnail
    clip = VideoFileClip(video_path)
    best_frame, max_sharp = None, 0
    for t in range(0, int(clip.duration), 2):
        frame = clip.get_frame(t)
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        sharpness = cv2.Laplacian(gray, cv2.CV_64F).var()
        if sharpness > max_sharp:
            max_sharp, best_frame = sharpness, frame
    clip.close()

    thumb_path = os.path.join(repo_dir, "thumb.jpg")
    cv2.imwrite(thumb_path, cv2.cvtColor(best_frame, cv2.COLOR_RGB2BGR))
    thumbnail_url = generate_media_url(thumb_path, domain=domain, repository_dir=repo_dir)

    return {
        "title": title,
        "keywords": keywords,
        "category": category,
        "thumbnail_url": thumbnail_url
    }
def choose_category(kws):
    if any(k in kws for k in ["comedy", "skit", "funny", "humor"]):
        return "Comedy"
    if any(k in kws for k in ["news", "analysis", "report"]):
        return "News & Politics"
    if any(k in kws for k in ["music", "song", "album"]):
        return "Music"
    return "Entertainment"

def dict_example():
    return {
    "raw":[]
    "aggregated": {
        "aggregated": {
            "audio_path": None,
            "best_clip": {},
            "candidate_clips": None,
            "canonical_url": None,
            "category": None,
            "description": None,
            "duration": None,
            "hashtags": None,
            "id": None,
            "keywords": None,
            "publication_date": None,
            "schema_markup": None,
            "social_metadata": None,
            "source_flags": {},
            "thumbnails_ranked": None,
            "title": None,
            "transcript_excerpt": None,
            "uploader": {},
            "video_path": None
        },
        "aggregated_path": None,
        "best_clip": None,
        "best_clip_path": None,
        "hashtags": None,
        "hashtags_path": None,
        "metadata": None,
        "metadata_path": None,
        "total_path": None
    },
    "captions": None,
    "info": {
        "aggregated": {
            "aggregated": {
                "audio_path": None,
                "best_clip": {},
                "candidate_clips": None,
                "canonical_url": None,
                "category": None,
                "description": None,
                "duration": None,
                "hashtags": None,
                "id": None,
                "keywords": None,
                "publication_date": None,
                "schema_markup": None,
                "social_metadata": None,
                "source_flags": {},
                "thumbnails_ranked": None,
                "title": None,
                "transcript_excerpt": None,
                "uploader": {},
                "video_path": None
            },
            "aggregated_path": None,
            "best_clip": None,
            "best_clip_path": None,
            "hashtags": None,
            "hashtags_path": None,
            "metadata": None,
            "metadata_path": None,
            "total_path": None
        },
        "audio_format": None,
        "audio_path": None,
        "captions": None,
        "created_at": None,
        "id": None,
        "info": {
            "_format_sort_fields": None,
            "_has_drm": None,
            "abr": None,
            "acodec": None,
            "age_limit": None,
            "aggregated_dir_aggregated_json_path": None,
            "aggregated_dir_aggregated_metadata_path": None,
            "aggregated_dir_best_clip_path": None,
            "aggregated_dir_hashtags_path": None,
            "aggregated_directory": None,
            "aspect_ratio": None,
            "asr": None,
            "audio_channels": None,
            "audio_path": None,
            "automatic_captions": {},
            "availability": None,
            "average_rating": None,
            "captions_path": None,
            "categories": None,
            "channel": None,
            "channel_follower_count": None,
            "channel_id": None,
            "channel_is_verified": None,
            "channel_url": None,
            "chapters": None,
            "comment_count": None,
            "description": None,
            "directory": None,
            "display_id": None,
            "duration": None,
            "duration_string": None,
            "dynamic_range": None,
            "epoch": None,
            "ext": None,
            "extractor": None,
            "extractor_key": None,
            "filesize_approx": None,
            "format": None,
            "format_id": None,
            "format_note": None,
            "formats": None,
            "fps": None,
            "fulltitle": None,
            "heatmap": None,
            "height": None,
            "id": None,
            "info_path": None,
            "is_live": None,
            "language": None,
            "like_count": None,
            "live_status": None,
            "media_type": None,
            "metadata_path": None,
            "original_url": None,
            "playable_in_embed": None,
            "playlist": None,
            "playlist_index": None,
            "protocol": None,
            "release_timestamp": None,
            "release_year": None,
            "requested_formats": None,
            "requested_subtitles": None,
            "resolution": None,
            "schema_paths": {
                "aggregated_dir": {
                    "aggregated_json_path": None,
                    "aggregated_metadata_path": None,
                    "best_clip_path": None,
                    "hashtags_path": None
                },
                "aggregated_directory": None,
                "audio_path": None,
                "captions_path": None,
                "info_path": None,
                "metadata_path": None,
                "thumbnail_path": None,
                "thumbnails_dir": {
                    "frames": None
                },
                "thumbnails_directory": None,
                "thumbnails_path": None,
                "total_aggregated_path": None,
                "total_info_path": None,
                "video_path": None,
                "whisper_path": None
            },
            "stretched_ratio": None,
            "subtitles": {},
            "tags": None,
            "tbr": None,
            "thumbnail": None,
            "thumbnail_path": None,
            "thumbnails": None,
            "thumbnails_dir_frames": None,
            "thumbnails_directory": None,
            "thumbnails_path": None,
            "timestamp": None,
            "title": None,
            "total_aggregated_path": None,
            "total_info_path": None,
            "upload_date": None,
            "uploader": None,
            "uploader_id": None,
            "uploader_url": None,
            "vbr": None,
            "vcodec": None,
            "video_id": None,
            "video_path": None,
            "view_count": None,
            "was_live": None,
            "webpage_url": None,
            "webpage_url_basename": None,
            "webpage_url_domain": None,
            "whisper_path": None,
            "width": None
        },
        "metadata": {
            "category": None,
            "keywords": None,
            "summary": None,
            "title": None
        },
        "metatags": {
            "canonical": None,
            "description": None,
            "description_html": None,
            "keywords": None,
            "og": {
                "description": None,
                "image": None,
                "image_alt": None,
                "image_height": None,
                "image_type": None,
                "image_width": None,
                "locale": None,
                "site_name": None,
                "title": None,
                "type": None,
                "url": None,
                "video": None
            },
            "other": {
                "application-name": None,
                "author": None,
                "bingbot": None,
                "charset": None,
                "color_scheme": None,
                "content_type": None,
                "distribution": None,
                "googlebot": None,
                "manifest": None,
                "rating": None,
                "revisit-after": None,
                "robots": None,
                "theme_color": None,
                "viewport": None,
                "yahooContent": None
            },
            "schema_markup": {
                "@context": None,
                "@type": None,
                "contentUrl": None,
                "description": None,
                "duration": None,
                "keywords": None,
                "name": None,
                "thumbnailUrl": None,
                "uploadDate": None
            },
            "thumbnail": None,
            "thumbnail_link": None,
            "thumbnail_resized_link": None,
            "title": None,
            "twitter": {
                "card": None,
                "creator": None,
                "description": None,
                "domain": None,
                "image": None,
                "image_alt": None,
                "image_type": None,
                "site": None,
                "title": None
            },
            "variants": None
        },
        "pagedata": {
            "seo": {
                "canonical": None,
                "description": None,
                "description_html": None,
                "keywords": None,
                "og": {
                    "description": None,
                    "image": None,
                    "image_alt": None,
                    "image_height": None,
                    "image_type": None,
                    "image_width": None,
                    "locale": None,
                    "site_name": None,
                    "title": None,
                    "type": None,
                    "url": None,
                    "video": None
                },
                "other": {
                    "application-name": None,
                    "author": None,
                    "bingbot": None,
                    "charset": None,
                    "color_scheme": None,
                    "content_type": None,
                    "distribution": None,
                    "googlebot": None,
                    "manifest": None,
                    "rating": None,
                    "revisit-after": None,
                    "robots": None,
                    "theme_color": None,
                    "viewport": None,
                    "yahooContent": None
                },
                "schema_markup": {
                    "@context": None,
                    "@type": None,
                    "contentUrl": None,
                    "description": None,
                    "duration": None,
                    "keywords": None,
                    "name": None,
                    "thumbnailUrl": None,
                    "uploadDate": None
                },
                "thumbnail": None,
                "thumbnail_link": None,
                "thumbnail_resized_link": None,
                "title": None,
                "twitter": {
                    "card": None,
                    "creator": None,
                    "description": None,
                    "domain": None,
                    "image": None,
                    "image_alt": None,
                    "image_type": None,
                    "site": None,
                    "title": None
                },
                "variants": None
            },
            "video": {
                "comment_count": None,
                "description": None,
                "duration": None,
                "file_name": None,
                "keywords": None,
                "keywords_str": None,
                "like_count": None,
                "optimized_video_url": None,
                "repost_count": None,
                "thumbnail": None,
                "title": None,
                "upload_date": None,
                "uploader": None,
                "uploader_id": None,
                "uploader_url": None,
                "video_url": None,
                "view_count": None,
                "webpage_url": None
            }
        },
        "seodata": {
            "seo_data": {
                "canonical_url": None,
                "categories": {},
                "category": None,
                "duration_formatted": None,
                "duration_seconds": None,
                "keywords_str": None,
                "publication_date": None,
                "schema_markup": {
                    "@context": None,
                    "@type": None,
                    "contentUrl": None,
                    "description": None,
                    "duration": None,
                    "keywords": None,
                    "name": None,
                    "thumbnailUrl": None,
                    "uploadDate": None
                },
                "seo_description": None,
                "seo_tags": None,
                "seo_title": None,
                "social_metadata": {
                    "og:description": None,
                    "og:image": None,
                    "og:title": None,
                    "og:video": None,
                    "twitter:card": None,
                    "twitter:description": None,
                    "twitter:image": None,
                    "twitter:title": None
                },
                "thumbnail": {
                    "alt_text": None,
                    "file_path": None
                },
                "uploader": {
                    "name": None,
                    "url": None
                },
                "video_metadata": {
                    "file_size_mb": None,
                    "format": None,
                    "resolution": None
                }
            }
        },
        "thumbnails": {
            "paths": None,
            "texts": None
        },
        "total_info": None,
        "updated_at": None,
        "video_id": None,
        "whisper": {
            "language": None,
            "segments": None,
            "text": None
        }
    },
    "metadata": {
        "category": None,
        "keywords": None,
        "summary": None,
        "title": None
    },
    "metatags": {
        "canonical": None,
        "description": None,
        "description_html": None,
        "keywords": None,
        "og": {
            "description": None,
            "image": None,
            "image_alt": None,
            "image_height": None,
            "image_type": None,
            "image_width": None,
            "locale": None,
            "site_name": None,
            "title": None,
            "type": None,
            "url": None,
            "video": None
        },
        "other": {
            "application-name": None,
            "author": None,
            "bingbot": None,
            "charset": None,
            "color_scheme": None,
            "content_type": None,
            "distribution": None,
            "googlebot": None,
            "manifest": None,
            "rating": None,
            "revisit-after": None,
            "robots": None,
            "theme_color": None,
            "viewport": None,
            "yahooContent": None
        },
        "schema_markup": {
            "@context": None,
            "@type": None,
            "contentUrl": None,
            "description": None,
            "duration": None,
            "keywords": None,
            "name": None,
            "thumbnailUrl": None,
            "uploadDate": None
        },
        "thumbnail": None,
        "thumbnail_link": None,
        "thumbnail_resized_link": None,
        "title": None,
        "twitter": {
            "card": None,
            "creator": None,
            "description": None,
            "domain": None,
            "image": None,
            "image_alt": None,
            "image_type": None,
            "site": None,
            "title": None
        },
        "variants": None
    },
    "pagedata": {
        "seo": {
            "canonical": None,
            "description": None,
            "description_html": None,
            "keywords": None,
            "og": {
                "description": None,
                "image": None,
                "image_alt": None,
                "image_height": None,
                "image_type": None,
                "image_width": None,
                "locale": None,
                "site_name": None,
                "title": None,
                "type": None,
                "url": None,
                "video": None
            },
            "other": {
                "application-name": None,
                "author": None,
                "bingbot": None,
                "charset": None,
                "color_scheme": None,
                "content_type": None,
                "distribution": None,
                "googlebot": None,
                "manifest": None,
                "rating": None,
                "revisit-after": None,
                "robots": None,
                "theme_color": None,
                "viewport": None,
                "yahooContent": None
            },
            "schema_markup": {
                "@context": None,
                "@type": None,
                "contentUrl": None,
                "description": None,
                "duration": None,
                "keywords": None,
                "name": None,
                "thumbnailUrl": None,
                "uploadDate": None
            },
            "thumbnail": None,
            "thumbnail_link": None,
            "thumbnail_resized_link": None,
            "title": None,
            "twitter": {
                "card": None,
                "creator": None,
                "description": None,
                "domain": None,
                "image": None,
                "image_alt": None,
                "image_type": None,
                "site": None,
                "title": None
            },
            "variants": None
        },
        "video": {
            "comment_count": None,
            "description": None,
            "duration": None,
            "file_name": None,
            "keywords": None,
            "keywords_str": None,
            "like_count": None,
            "optimized_video_url": None,
            "repost_count": None,
            "thumbnail": None,
            "title": None,
            "upload_date": None,
            "uploader": None,
            "uploader_id": None,
            "uploader_url": None,
            "video_url": None,
            "view_count": None,
            "webpage_url": None
        }
    },
    "seodata": {
        "seo_data": {
            "canonical_url": None,
            "categories": {},
            "category": None,
            "duration_formatted": None,
            "duration_seconds": None,
            "keywords_str": None,
            "publication_date": None,
            "schema_markup": {
                "@context": None,
                "@type": None,
                "contentUrl": None,
                "description": None,
                "duration": None,
                "keywords": None,
                "name": None,
                "thumbnailUrl": None,
                "uploadDate": None
            },
            "seo_description": None,
            "seo_tags": None,
            "seo_title": None,
            "social_metadata": {
                "og:description": None,
                "og:image": None,
                "og:title": None,
                "og:video": None,
                "twitter:card": None,
                "twitter:description": None,
                "twitter:image": None,
                "twitter:title": None
            },
            "thumbnail": {
                "alt_text": None,
                "file_path": None
            },
            "uploader": {
                "name": None,
                "url": None
            },
            "video_metadata": {
                "file_size_mb": None,
                "format": None,
                "resolution": None
            }
        }
    },
    "thumbnails": {
        "paths": None,
        "texts": None
    },
    "whisper": {
        "language": None,
        "segments": None,
        "text": None
    }
}
