import json
import logging
import re

logger = logging.getLogger(__name__)

def get_info_json(token_data):
    """Get infoJson from token_data"""
    if hasattr(token_data, 'infoJson') and token_data.infoJson:
        return token_data.infoJson
    
    # Log the issue for debugging
    logger.warning("infoJson attribute missing or empty in token_data")
    logger.info(f"Available attributes: {[attr for attr in dir(token_data) if not attr.startswith('__') and not callable(getattr(token_data, attr))]}")
    
    return "{}"

def is_valid_json(json_str):
    """Check if a string is valid JSON and not empty"""
    if not json_str or json_str == "{}" or json_str == "":
        return False
        
    try:
        data = json.loads(json_str)
        # Check if it's an empty object
        if isinstance(data, dict) and not data:
            return False
        # Check if it has at least some basic fields
        if isinstance(data, dict) and ('id' in data or 'title' in data):
            return True
        # Check if it has token_data which is important
        if isinstance(data, dict) and 'token_data' in data and data['token_data']:
            return True
        return True
    except Exception as e:
        logger.warning(f"Invalid JSON: {e}")
        return False

def extract_video_id(url):
    """Extract video ID from a YouTube URL"""
    # If it's already a video ID
    if re.match(r'^[a-zA-Z0-9_-]{11}$', url):
        return url
    
    # Handle youtu.be URLs
    youtu_be_match = re.search(r'youtu\.be/([a-zA-Z0-9_-]{11})', url)
    if youtu_be_match:
        return youtu_be_match.group(1)
    
    # Handle youtube.com URLs
    youtube_match = re.search(r'(?:youtube\.com/(?:watch\?v=|embed/|v/)|youtube\.com/.*[?&]v=)([a-zA-Z0-9_-]{11})', url)
    if youtube_match:
        return youtube_match.group(1)
    
    # Handle shorts URLs
    shorts_match = re.search(r'youtube\.com/shorts/([a-zA-Z0-9_-]{11})', url)
    if shorts_match:
        return shorts_match.group(1)
    
    return None
